python 线程中join方法的使用

1、作用:让子线程插入主线程,可理解为在在join调用处把子线程的code move到了主线程,直到被插入的code运行结束,主线程接着下面的继续代码运行

2、触发条件:手动调用或主线程要退出时自动调用

3、参数说明:join方法可可传入参数表示子线程加入主线程的运行时间,超出此时间,强制结束子线程,不传参数表示时间不限!

4、example

a) 主线程代码将要结束时自动调用       

from threading import Thread
import threading
from time import sleep
import signal
import traceback
import sys
import os

class DataGenerator(Thread):
    def __init__(self, topic_dir):
        self.topic_dir = topic_dir
        self.stopFlag = False
        threading.Thread.__init__(self, name="thread_generator_")

    def run(self):
        self.stoped = False
        while not self.stopFlag:
            print "test_data"
            shell_cmd = "sh /usr/local/data_generator/do.sh " + self.topic_dir
           # os.system(shell_cmd)
            print "runing.....\n"
            sleep(1)
        self.stoped = True
   #join 方法会在主线程运行到末尾时调用,它让其所在线程加入到主线程运行,直到线程运行结束,主线程才退出
    def join(self, timeout=None):
        self.stopFlag = True
        while not self.stoped:
            print "waiting for stopped\n"
            sleep(1)
        threading.Thread.join(self, timeout)


if __name__ == "__main__":
    if len(sys.argv) < 2:
        print "please set the topic_dirs \n"
        os._exit(-1)
    stop_flag = False
    generators = []
    for topic_dir in sys.argv[1:]:
        generator = DataGenerator(topic_dir)
        generators.append(generator)
    for g in generators:
        g.start()

    print "start finished!\n"

    # while not stop_flag:
    #     sleep(1)
    # sleep(2)

b) 主线程结束前,手动调用join(通过信号量调用)

from threading import Thread
import threading
from time import sleep
import signal
import traceback
import sys
import os

class DataGenerator(Thread):
    def __init__(self, topic_dir):
        self.topic_dir = topic_dir
        self.stopFlag = False
        threading.Thread.__init__(self, name="thread_generator_")

    def run(self):
        self.stoped = False
        while not self.stopFlag:
            print "test_data"
            shell_cmd = "sh /usr/local/data_generator/do.sh " + self.topic_dir
           # os.system(shell_cmd)
            print "runing.....\n"
            sleep(1)
        self.stoped = True
   #join 方法会在主线程运行到末尾时调用,它让其所在线程加入到主线程运行,直到线程运行结束,主线程才退出
    def join(self, timeout=None):
        self.stopFlag = True
        while not self.stoped:
            print "waiting for stopped\n"
            sleep(1)
        threading.Thread.join(self, timeout)


if __name__ == "__main__":
    if len(sys.argv) < 2:
        print "please set the topic_dirs \n"
        os._exit(-1)
    stop_flag = False
    generators = []
    for topic_dir in sys.argv[1:]:
        generator = DataGenerator(topic_dir)
        generators.append(generator)

    def stop(n=0, e=0):
        global stop_flag
        for g in generators:
            #logger.error("stopping " + str(t))
            try:
                g.join(60)
            except:
                print traceback.format_exc()
                #logger.error(traceback.format_exc())
        stop_flag = True

    #ctrl+c
    signal.signal(signal.SIGTERM, stop)
    #kill
    signal.signal(signal.SIGINT, stop)
    for g in generators:
        g.start()

    print "start finished!\n"

    while not stop_flag:
         sleep(1)
    # sleep(2)
    print "stop finished!\n"
5 、总结:以上代码可在win linux上正常运行,over!

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python ,可以使用线程列表和 join() 方法来实现多线程编程。 线程列表是一个包含多个线程对象的列表。每个线程对象都可以执行一个函数或方法join() 方法用于等待所有线程完成。当所有线程完成后,join() 方法返回。 以下是一个简单的示例,使用线程列表和 join() 方法实现多线程编程: ```python import threading # 定义一个线程类,继承自 threading.Thread class MyThread(threading.Thread): def __init__(self, num): threading.Thread.__init__(self) self.num = num def run(self): print("Thread " + str(self.num) + " started") # 线程执行的代码 print("Thread " + str(self.num) + " finished") # 创建一个线程列表 threads = [] # 创建 5 个线程 for i in range(5): t = MyThread(i) threads.append(t) # 启动所有线程 for t in threads: t.start() # 等待所有线程完成 for t in threads: t.join() print("All threads finished") ``` 在上面的例子,我们创建了一个 MyThread 类,它继承自 threading.Thread 类。MyThread 类的构造函数接受一个参数 num,用于标识线程。run() 方法线程执行的方法,我们在这里打印线程的编号和一些消息。 接下来,我们创建了一个线程列表 threads,并向其添加 5 个 MyThread 对象。然后,我们启动所有线程,并使用 join() 方法等待所有线程完成。最后,我们打印一条消息,表示所有线程都已完成。 注意,在 Python 线程列表和 join() 方法可以用于控制线程的执行顺序和并发性。如果需要更高级的线程控制,可以使用 Python 线程锁、条件变量、信号量等同步原语。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值