首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > perl python >

python 线程代码,求指导

2013-01-09 
python 线程代码,求指点__author__ root#encoding:utf8import threading,string,time#假设这个函数要

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)

热点排行