python threading中处理主进程和子线程的关系
之前用Python的多线程,总是处理不好进程和线程之间的关系。后来发现了join和setDaemon函数,才终于弄明白。下面总结一下。
1.使用join函数后,主进程会在调用join的地方等待子线程结束,然后才接着往下执行。
join使用实例如下:
[python] view plain copy
- import time
- import random
- import threading
- class worker(threading.Thread):
- def __init__(self):
- threading.Thread.__init__(self)
- def run(self):
- t = random.randint(1,10)
- time.sleep(t)
- print "This is " + self.getName() + ";I sleep %d second."%(t)
- tsk = []
- for i in xrange(0,5):
- time.sleep(0.1)
- thread = worker()
- thread.start()
- tsk.append(thread)
- for tt in tsk:
- tt.join()
- print "This is the end of main thread."
运行结果如下:[python] view plain copy
- # python testjoin.py
- This is Thread-3;I sleep 2 second.
- This is Thread-1;I sleep 4 second.
- This is Thread-2;I sleep 7 second.
- This is Thread-4;I sleep 7 second.
- This is Thread-5;I sleep 7 second.
- This is the end of main thread.
这里创建了5个子线程,每个线程随机等待1-10秒后打印退出;主线程分别等待5个子线程结束。最后结果是先显示各个子线程,再显示主进程的结果。
2. 如果使用的setDaemon函数,则与join相反,主进程结束的时候不会等待子线程。
setDaemon函数使用实例:
[python] view plain copy
- import time
- import random
- import threading
- class worker(threading.Thread):
- def __init__(self):
- threading.Thread.__init__(self)
- def run(self):
- t = random.randint(1,10)
- time.sleep(t)
- print "This is " + self.getName() + ";I sleep %d second."%(t)
- tsk = []
- for i in xrange(0,5):
- time.sleep(0.1)
- thread = worker()
- thread.setDaemon(True)
- thread.start()
- tsk.append(thread)
- print "This is the end of main thread."
这里设置主进程为守护进程,当主进程结束的时候,子线程被中止
运行结果如下:
[python] view plain copy
- #python testsetDaemon.py
- This is the end of main thread.
3、如果没有使用join和setDaemon函数,则主进程在创建子线程后,直接运行后面的代码,主程序一直挂起,直到子线程结束才能结束。
[python] view plain copy
- import time
- import random
- import threading
- class worker(threading.Thread):
- def __init__(self):
- threading.Thread.__init__(self)
- def run(self):
- t = random.randint(1,10)
- time.sleep(t)
- print "This is " + self.getName() + ";I sleep %d second."%(t)
- tsk = []
- for i in xrange(0,5):
- time.sleep(0.1)
- thread = worker()
- thread.start()
- tsk.append(thread)
- print "This is the end of main thread."
运行结果如下:[python] view plain copy
- # python testthread.py
- This is the end of main thread.
- This is Thread-4;I sleep 1 second.
- This is Thread-3;I sleep 7 second.
- This is Thread-5;I sleep 7 second.
- This is Thread-1;I sleep 10 second.
- This is Thread-2;I sleep 10 second.
相关推荐
YENCSDN 2020-11-17
lsjweiyi 2020-11-17
houmenghu 2020-11-17
Erick 2020-11-17
HeyShHeyou 2020-11-17
以梦为马不负韶华 2020-10-20
lhtzbj 2020-11-17
夜斗不是神 2020-11-17
pythonjw 2020-11-17
dingwun 2020-11-16
lhxxhl 2020-11-16
坚持是一种品质 2020-11-16
染血白衣 2020-11-16
huavhuahua 2020-11-20
meylovezn 2020-11-20
逍遥友 2020-11-20
weiiron 2020-11-16