Python THREADING模块中的JOIN()方法深入理解
看了oschina上的两个代码,受益匪浅。其中对join()方法不理解,看python官网文档的介绍: 哈哈,这个易懂。 复制代码 代码如下: #-*- encoding: gb2312 -*- import string,threading,time 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 # 创建4个线程 main(4) ################################################################### #-*- encoding: gb2312 -*- import threading import 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,count time.sleep(1) if __name__ == '__main__': global count,mutex threads = [] num = 4 count = 1 # 创建锁 mutex = threading.Lock() # 创建线程对象 for x in xrange(0,num): threads.append(Test(10)) # 启动线程 for t in threads: t.start() # 等待子线程结束 for t in threads: t.join() 在程序中,最后join()方法的调用就明白了,是主进程挨个调用子线程的join()方法。当四个线程都执行完毕后,主线程才会执行下面的代码,在这里也就是退出了。 setDaemon() 这个方法基本和join是相反的。当我们在程序运行中,执行一个主线程,如果主线程又创建一个子线程,主线程和子线程就分兵两路,分别运行,那么当主线程完成想退出时,会检验子线程是否完成。如果子线程未完成,则主线程会等待子线程完成后再退出。但是有时候我们需要的是,只要主线程完成了,不管子线程是否完成,都要和主线程一起退出,这时就可以用setDaemon方法啦 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |