python线程setDaemon

在python中,主线程结束后,会默认等待子线程结束后,主线程才退出,如下:

#coding=utf-8
import threading
import time


class mythread(threading.Thread):
	def __init__(self):
		super().__init__()
	
	def run(self):
		for i in range(5):
			time.sleep(1)
		print("mythread end")


if __name__ == "__main__":
	print("main start")
	thd = mythread()
	thd.setDaemon(True)   ##主线程在结束时结束子线程thd
	thd.start()
如下面生产者、消费者模型,queue.get()队列为空时阻塞,线程consumer1还是被退出,但不会输出"consumer end"

#coding=utf-8
import time
import threading
import queue

class producer(threading.Thread):
	def __init__(self,work_queue):
		super().__init__()             ##父类初始化
		self.work_queue = work_queue
	def run(self):
		num = 10
		while (num > 0):
			self.work_queue.put(num)
			num = num - 1
			time.sleep(1)
		print("producer end")

class consumer(threading.Thread):
	def __init__(self,work_queue):
		super(consumer,self).__init__()   ##父类初始化
		self.work_queue = work_queue
	def run(self):
		while True:
			num = self.work_queue.get()  ##queue为空时阻塞
			print("get: " + str(num))
		print("consumer end")

def main():
	work_queue = queue.Queue()
	producer1 = producer(work_queue)
	producer1.start()

	consumer1 = consumer(work_queue)
	consumer1.setDaemon(True)
	consumer1.start()

	##work_queue.join()

if __name__ == '__main__':
	main()
E:\MySelf\myfile\My Python>threadtest.py
get: 10
get: 9
get: 8
get: 7
get: 6
get: 5
get: 4
get: 3
get: 2
get: 1
producer end

E:\MySelf\myfile\My Python>




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值