美文网首页
python学习笔记(6)多线程join的用法及全局锁

python学习笔记(6)多线程join的用法及全局锁

作者: 海的那一边 | 来源:发表于2019-04-28 15:18 被阅读0次

1.join([time]): 等待至线程中止
1)如果子线程不添加join,则主线程可能运行完毕了子线程还没有结束

image.png

例如:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import threading
import time


class myThread(threading.Thread):  # 继承父类threading.Thread
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter

    def run(self):  # 把要执行的代码写到run函数里面 线程在创建后会直接运行run函数
        print "Starting " + self.name
        print_time(self.name, self.counter, 5)
        print "Exiting " + self.name


def print_time(threadName, delay, counter):
    while counter:

        time.sleep(delay)
        print "%s: %s" % (threadName, time.ctime(time.time()))
        counter -= 1
        global sum_count
        # lock.acquire()
        sum_count += 1
        print "sum_count:" + str(sum_count) + "\n"
        # lock.release()

if __name__ == '__main__':

    sum_count = 0
    thread_list = []
    lock = threading.Lock()
    for i in range(1, 10):
        thread = myThread(i, "Thread" + str(i), 0)
        thread_list.append(thread)
    for thread in thread_list:
        thread.start()
    # for thread in thread_list:
    #     thread.join()
    # for thread in thread_list:
    #     thread.start()
    #     thread.join()


    print '结束'

上述'结束'可能出现在结果中的某些线程结束之前。
2)所有子线程线程start之后再给子线程添加join,则主线程会等待所有线程执行结束再运行后面的语句


image.png

例如,把一下语句的注释去掉,则与运行结果的最后会打印“结束”

 for thread in thread_list:
        thread.join()

3)每个子线程start之后给子线程添加join,则每个子线程都会等待上个线程执行结束。


image.png

例如:将代码进行如下修改:

# for thread in thread_list:
    #     thread.start()
    # for thread in thread_list:
    #     thread.join()
    for thread in thread_list:
        thread.start()
        thread.join()

则子线程会上一个子线程结束了再开始下一个子线程,所有子线程都结束后再打印‘“结束”
4)如果加了参数time
当设置守护线程时,含义是主线程对于子线程等待timeout的时间将会杀死该子线程,最后退出程序。所以说,如果有10个子线程,全部的等待时间就是每个timeout的累加和。简单的来说,就是给每个子线程一个timeout的时间,让他去执行,时间一到,不管任务有没有完成,直接杀死。
没有设置守护线程时,主线程将会等待timeout的累加和这样的一段时间,时间一到,主线程结束,但是并没有杀死子线程,子线程依然可以继续执行,直到子线程全部结束,程序退出。

2.全局锁
如果上述程序没有给sum_count加全局锁,则有可能出现运行结果不正确的情况,我们的预期是sum_count = 45,但是有可能出现某两个线程同时操作sum_count的情况,导致执行结果sum_count小于45。
这时我们定义一个锁:lock = threading.Lock(),并且在sum_count前后获取锁和释放锁,就可以避免结果出错。

        lock.acquire()
        sum_count += 1
        print "sum_count:" + str(sum_count) + "\n"
        lock.release()

相关文章

网友评论

      本文标题:python学习笔记(6)多线程join的用法及全局锁

      本文链接:https://www.haomeiwen.com/subject/yeidnqtx.html