600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > Python实战之多线程编程thread模块

Python实战之多线程编程thread模块

时间:2019-02-23 03:48:32

相关推荐

Python实战之多线程编程thread模块

Python实战之多线程编程thread模块

在Python中除了可以通过继承threading.Thread类来实现多线程外,也可以调用thread模块中的start_new_thread()函数来产生新的线程,如下

[python]view plaincopyprint?importtime,thread deftimer(): print('hello') deftest(): foriinrange(0,10): thread.start_new_thread(timer,()) if__name__=='__main__': test() time.sleep(10)

或者

[python]view plaincopyprint?importtime,thread deftimer(name=None,group=None): print('name:'+name+',group:'+group) deftest(): foriinrange(0,10): thread.start_new_thread(timer,('thread'+str(i),'group'+str(i))) if__name__=='__main__': test() time.sleep(10)

这个是thread.start_new_thread(function,args[,kwargs])函数原型,其中function参数是你将要调用的线程函数;args是讲传递给你的线程函数的参数,他必须是个tuple类型;而kwargs是可选的参数。线程的结束一般依靠线程函数的自然结束;也可以在线程函数中调用thread.exit(),他抛出SystemExit exception,达到退出线程的目的。

下面来看一下thread中的锁机制,如下两段代码:

代码一

[python]view plaincopyprint?importtime,thread count=0 deftest(): globalcount foriinrange(0,10000): count+=1 foriinrange(0,10): thread.start_new_thread(test,()) time.sleep(5) printcount

代码二

[python]view plaincopyprint?importtime,thread count=0 lock=thread.allocate_lock() deftest(): globalcount,lock lock.acquire() foriinrange(0,10000): count+=1 lock.release() foriinrange(0,10): thread.start_new_thread(test,()) time.sleep(5) printcount

代码一中的值由于没有使用lock机制,所以是多线程同时访问全局的count变量,导致最终的count结果不是10000*10,而代码二中由于是使用了锁,从而保证了同一个时间只能有一个线程修改count的值,所以最终结果是10000*10.

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。