python 线程之 threading(一)

threading:基于对象和类的较高层面上的接口,threading模块在内部使用_thread模块来实现线程的对象以及常用的同步化工具的功能。

使用定制类的方式继承 threading.Thread基类

    1. 在子类中需要override __init__ 和 run() 方法。

    2. 当创建这个子类的实例后调用start方法,run方法将在新的线程中的Thread框架下运行。

    3. join方法的使用:等待线程退出(当在一个线程中调用另外一个线程的join方式之后,调用线程会阻塞等待调用join线程退出之后在继续运行)

    4. 使用threading.Lock()创建同步锁,使用这种方式创建的锁和_thread_allocate_lock方法创建的锁相同。

 1 import threading
 2 
 3 class MyThread(threading.Thread):
 4     def __init__(self, myId, count, mutex):
 5         self.myId = myId
 6         self.count = count
 7         self.mutex = mutex
 8         threading.Thread.__init__(self)
 9 
10     def run(self):
11         for i in range(self.count):
12             with self.mutex:
13                 print('{0} id => {1}'.format(self.myId, i))
14 
15 
16 mutex = threading.Lock()
17 threads = []
18 
19 for i in range(10):
20     thread = MyThread(i, 100, mutex)
21     threads.append(thread)
22 
23 for thread in threads:
24     thread.start()
25     thread.join()
26 print('main process existing')
View Code

使用threading模块调用线程的其他方法:

I  同上,使用Thread子类的方式开启新的线程

II 传入行为

1 import threading
2 
3 
4 def action(num):
5     print("the execute num is", num)
6 
7 thread = threading.Thread(target=(lambda: action(2)))
8 thread.start()
View Code

III 传入行为,但是不使用lambda函数封装起来

threading.Thread(target=action, args=(2,)).start()

 

posted @ 2016-12-20 22:36  someOneHan  阅读(304)  评论(0编辑  收藏  举报