标签:done thread join __init__ count 区别 存在 定义 平衡
进程的开启必须是在main下开启,但是线程的开启不是一定在main下开启
第一种:在main下开启,和进程的开启方式一样
1 1.创建线程的开销比创建进程的开销小,因而创建线程的速度快
2 from multiprocessing import Process
3 from threading import Thread
4 import os
5 import time
6 def work():
7 print('<%s> is running'%os.getpid())
8 time.sleep(2)
9 print('<%s> is done'%os.getpid())
11 if __name__ == '__main__':
12 t=Thread(target=work,)
14 t.start()
15 print('主',os.getpid())
第二种:继承与Thread类方式的开启
1 from threading import Thread
2 import time
3 class Work(Thread):
4 def __init__(self,name):
5 super().__init__()
6 self.name = name
7 def run(self):
8 # time.sleep(2)
9 print('%s say hell'%self.name)
10 if __name__ == '__main__':
11 t = Work('egon')
12 t.start()
13 print('主')
Thread实例对象方法
threading模块提供的一些方法
其他属性
1 from threading import Thread
2 from multiprocessing import Process
3 import time,os,threading
4 def work():
5 time.sleep(2)
6 print('%s is running' % threading.currentThread().getName())
7 print(threading.current_thread()) #其他线程
8 print(threading.currentThread().getName()) #得到其他线程的名字
9 if __name__ == '__main__':
10 t = Thread(target=work)
11 t.start()
12
13 print(threading.current_thread().getName()) #主线程的名字
14 print(threading.current_thread()) #主线程
15 print(threading.enumerate()) #连同主线程在内有两个运行的线程
16 time.sleep(2)
17 print(t.is_alive()) #判断线程是否存活
18 print(threading.activeCount())
19 print('主')
join与守护线程
守护线程与守护进程的区别
实例
from multiprocessing import Process
from threading import Thread,currentThread
import time,os
def talk1():
time.sleep(2)
print('hello')
def talk2():
time.sleep(2)
print('you see see')
if __name__ == '__main__':
t1 = Thread(target=talk1)
t2 = Thread(target=talk2)
# t1 = Process(target=talk1)
# t2 = Process(target=talk2)
t1.daemon = True
t1.start()
t2.start()
print('主线程',os.getpid())
########################################
主线程 11288
you see see
hello
###############或者##################3
主线程 5664
hello
you see see
#3 --------迷惑人的例子
from threading import Thread
import time
def foo():
print(123)
# time.sleep(10) #如果这个等的时间大于下面等的时间,就把不打印end123了
time.sleep(2) #如果这个等的时间小于等于下面等的时间,就把end123也打印了
print('end123')
def bar():
print(456)
# time.sleep(5)
time.sleep(10)
print('end456')
if __name__ == '__main__':
t1 = Thread(target=foo)
t2 = Thread(target=bar)
t1.daemon = True #主线程运行完了守护的那个还没有干掉,
# 主线程等非守护线程全都结束它才结束
t1.start()
t2.start()
print('main---------')
#############大于##################
123
456
main---------
end456
##############小于等于#############
123
456
main---------
end123
end456
标签:done thread join __init__ count 区别 存在 定义 平衡
原文地址:https://www.cnblogs.com/daviddd/p/12034410.html