Python THREADING模块中的JOIN()方法深入理解

WBOY
Release: 2016-06-10 15:17:45
Original
1136 people have browsed it

看了oschina上的两个代码,受益匪浅。其中对join()方法不理解,看python官网文档的介绍:
join([timeout]):等待直到进程结束。这将阻塞正在调用的线程,直到被调用join()方法的线程结束。(好难翻译,应该是这个意思)

哈哈,这个易懂。
join方法,如果一个线程或者一个函数在执行过程中要调用另外一个线程,并且待到其完成以后才能接着执行,那么在调用这个线程时可以使用被调用线程的join方法。

复制代码 代码如下:

#-*- 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, x, 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()方法。当四个线程都执行完毕后,主线程才会执行下面的代码,在这里也就是退出了。
相对应的在网上一起找到的另一个方法:
3.守护进程

setDaemon()

这个方法基本和join是相反的。当我们在程序运行中,执行一个主线程,如果主线程又创建一个子线程,主线程和子线程就分兵两路,分别运行,那么当主线程完成想退出时,会检验子线程是否完成。如果子线程未完成,则主线程会等待子线程完成后再退出。但是有时候我们需要的是,只要主线程完成了,不管子线程是否完成,都要和主线程一起退出,这时就可以用setDaemon方法啦

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!