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()
时间: 2024-10-14 21:09:44