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

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

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

[python]  view plain copy print ?
  1. import time, thread  
  2. def timer():  
  3.     print('hello')  
  4. def test():  
  5.     for i in range(010):  
  6.         thread.start_new_thread(timer, ())  
  7. if __name__=='__main__':  
  8.     test()  
  9.     time.sleep(10)  
 

或者

[python]  view plain copy print ?
  1. import time, thread  
  2. def timer(name=None, group=None):  
  3.     print('name: ' + name + ', group: ' + group)  
  4. def test():  
  5.     for i in range(010):  
  6.         thread.start_new_thread(timer, ('thread' + str(i), 'group' + str(i)))  
  7. if __name__=='__main__':  
  8.     test()  
  9.     time.sleep(10)  
 

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

 

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

代码一

[python]  view plain copy print ?
  1. import time, thread  
  2. count = 0  
  3. def test():  
  4.     global count  
  5.       
  6.     for i in range(010000):  
  7.         count += 1  
  8.       
  9. for i in range(010):  
  10.     thread.start_new_thread(test, ())  
  11. time.sleep(5)  
  12. print count  
 

代码二

[python]  view plain copy print ?
  1. import time, thread  
  2. count = 0  
  3. lock = thread.allocate_lock()  
  4. def test():  
  5.     global count, lock  
  6.     lock.acquire()  
  7.       
  8.     for i in range(010000):  
  9.         count += 1  
  10.       
  11.     lock.release()  
  12. for i in range(010):  
  13.     thread.start_new_thread(test, ())  
  14. time.sleep(5)  
  15. print count  
 

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值