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!