码迷,mamicode.com
首页 > 其他好文 > 详细

threading 模块

时间:2015-05-13 00:24:05      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:

threading模块里面主要是对一些线程的操作对象化了,创建了Thread class。使用线程有两种模式,一种是创建线程要执行的 函数,把这个函数传递进Thread对象里,让它来执行;另一种是直接从Thread继承,创建一个新的class,把线程执行的代码放到这个新的 class里。

 1 __author__ = Zechary
 2 import string, threading, time
 3 def thread_main(a):
 4     global count, mutex
 5     threadname = threading.current_thread().getName()
 6 
 7     for x in xrange(0, int(a)):
 8         mutex.acquire()
 9         count = count + 1
10         mutex.release()
11         print threadname, x, count
12         time.sleep(1)
13 
14 def run(num):
15     global  count, mutex
16     threads = []
17     count = 1
18     mutex = threading.Lock()
19     for x in xrange(0, num):
20         threads.append(threading.Thread(target=thread_main, args=(10,)))
21     for t in threads:
22         t.start()
23     for t in threads:
24         t.join()
25 
26 if __name__ == __main__:
27     num = 4
28     run(4)

继续类:

 1 __author__ = Zechary
 2 import threading
 3 import time
 4 
 5 class Test(threading.Thread):
 6     def __init__(self, num):
 7         threading.Thread.__init__(self)
 8         self.run_num = num
 9 
10     def run(self):
11         global count, mutex
12         threadname = threading.currentThread().getName()
13         for x in xrange(0, int(self.run_num)):
14             mutex.acquire()
15             count += 1
16             mutex.release()
17             print threadname, x, count
18             time.sleep(1)
19 
20 if __name__ == __main__:
21     global count, mutex
22     threads = []
23     num = 4
24     count =1
25     mutex = threading.Lock()
26     for x in xrange(0, num):
27         threads.append(Test(10))
28     for t in threads:
29         t.start()
30     for t in threads:
31         t.join()

 

threading 模块

标签:

原文地址:http://www.cnblogs.com/xiaojiangdraug/p/4498984.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!