python多线程
1.多线程方法
#!/usr/python
#thread
import string, threading, time
def thread_main(a):
#get thread name
global count, mutex
threadname = threading.currentThread().getName()
for x in xrange(0, int(a)):
#get lock
mutex.acquire()
count = count + 1
#release lock
mutex.release()
print threadname, x, count
time.sleep(1)
def main(num):
global count, mutex
threads = []
count = 1
#create lock
mutex = threading.Lock()
#create thread object
for x in xrange(0, num):
threads.append(threading.Thread(target = thread_main, args=(10,))
2.多线程类
import threading, time
class Test(threading.Thread):
def __init__(self, num):
threading.Thread.__init__(self)
self._run_num = num
def run(self):
global count, mutex
threadname = threading.currentThread().getName()
for x in xrange(0, int(self._run_num)):
mutex.acquire()
count = count + 1
mutex.release()
print threadname, x, count
time.sleep(1)
if __name__ == '__main__':
global count, mutex
threads = []
num = 4
count = 1
#create lock
mutex = threading.Lock()
#create thread object
for x in xrange(0, num):
threads.append(Test(10))
#start thread
for t in threads:
t.start()
#wait thread exist
for t in threads:
t.join()

浙公网安备 33010602011771号