Python实战之多线程编程thread模块
2011-02-17 08:14
471 查看
在Python中除了可以通过继承threading.Thread类来实现多线程外,也可以调用thread模块中的start_new_thread()函数来产生新的线程,如下
或者
这个是thread.start_new_thread(function,args[,kwargs])函数原型,其中function参数是你将要调用的线程函数;args是讲传递给你的线程函数的参数,他必须是个tuple类型;而kwargs是可选的参数。线程的结束一般依靠线程函数的自然结束;也可以在线程函数中调用thread.exit(),他抛出SystemExit exception,达到退出线程的目的。
下面来看一下thread中的锁机制,如下两段代码:
代码一
代码二
代码一中的值由于没有使用lock机制,所以是多线程同时访问全局的count变量,导致最终的count结果不是10000*10,而代码二中由于是使用了锁,从而保证了同一个时间只能有一个线程修改count的值,所以最终结果是10000*10.
import time, thread def timer(): print('hello') def test(): for i in range(0, 10): thread.start_new_thread(timer, ()) if __name__=='__main__': test() time.sleep(10)
或者
import time, thread def timer(name=None, group=None): print('name: ' + name + ', group: ' + group) def test(): for i in range(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中的锁机制,如下两段代码:
代码一
import time, thread count = 0 def test(): global count for i in range(0, 10000): count += 1 for i in range(0, 10): thread.start_new_thread(test, ()) time.sleep(5) print count
代码二
import time, thread count = 0 lock = thread.allocate_lock() def test(): global count, lock lock.acquire() for i in range(0, 10000): count += 1 lock.release() for i in range(0, 10): thread.start_new_thread(test, ()) time.sleep(5) print count
代码一中的值由于没有使用lock机制,所以是多线程同时访问全局的count变量,导致最终的count结果不是10000*10,而代码二中由于是使用了锁,从而保证了同一个时间只能有一个线程修改count的值,所以最终结果是10000*10.
相关文章推荐
- Python实战之多线程编程thread模块
- python的多线程编程 --- thread模块
- python多线程编程之thread模块
- Python:使用threading模块实现多线程编程一[综述]
- Python:使用threading模块实现多线程编程一[综述]
- Python:使用threading模块实现多线程编程一[综述]
- python多线程模块thread,threading,Queue
- [Python module]使用threading模块实现多线程编程一[综述]
- Python:thread模块用于多线程处理
- python多线程(2)--thread和threading模块的使用
- python多线程模块thread
- Python多线程编程使用Queue模块保持线程同步
- Python并发编程(1):多线程编程之thread和threading
- Python学习笔记--多线程编程,thread
- Python 多线程编程,thread
- [python] 专题八.多线程编程之thread和threading
- python多线程编程----threading模块
- Python多线程 - 使用_thread模块实现多线程
- python之潜心研究多线程(thread模块) 建议使用threading模块
- Python模块学习 ---- thread 多线程处理