python 线程代码,求指点
__author__ = 'root'
#encoding:utf8
import threading,string,time
#假设这个函数要运行90次,最大使用4个线程,下面的程序是全部启动
# 我要怎么限制4个线程,直至把这个函数运行完成?
def thread_main(a):
global count,mutex
threadname = threading.currentThread().getName()
for x in xrange(0,int(a)):
mutex.acquire()
count = count + 1
#释放锁
mutex.release()
print threadname,x,count
time.sleep(1)
def main(num):
global count,mutex
threads = []
count = 1
mutex = threading.Lock()
for x in xrange(0,num):
threads.append(threading.Thread(target=thread_main,args=(10,)))
#启动所有线程
for t in threads:
t.start()
for t in threads:
t.join()
if __name__ == '__main__':
num = 4
main(4)
def thread_main(a):
global count,mutex, count2, mutex2
threadname = threading.currentThread().getName()
while True:
mutex2.acquire()
count2 += 1
mutex2.release()
if count2 > 90:
return
for x in xrange(0,int(a)):
mutex.acquire()
count = count + 1
#释放锁
mutex.release()
print threadname,x,count
time.sleep(1)