进程开启方式和进程在所有子进程结束之后才结束
作者:互联网
1.主进程会等待所有子进程结束后才会程序结束
2.主线程也会等待所有子线程结束后才会主线程结束
3.from multiprocessing import Pool这个进程池,并不会等待所有的进程运行完成,而是主线程代码执行完成后程序就立即结束 所以这个进程池需要加p.close()和p.join()
4.from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor 的进程池和线程池,主进程或者主线程会等进程池内或者线程 池内的任务运行完成,整 个程序才会结束
5.协程的问题,所有协程,主线程必须加join()阻塞,否则其他协程不运行.
6.关于守护进程的问题,守护进程是在主进程的代码结束后,立刻结束.守护线程是在所有子线程都结束后,守护线程结束.
示例一:
import threading
from time import ctime, sleep
import time
def ListenMusic(name):
print ("Begin listening to %s. %s" %(name,ctime()))
sleep(8)
print("end listening to %s. %s" %(name,ctime()))
def RecordBlog(title):
print ("Begin recording the %s! %s" %(title,ctime()))
sleep(5)
print('end recording the %s! %s' %(title,ctime()))
threads = []
t1 = threading.Thread(target=ListenMusic,args=('水手',))
t2 = threading.Thread(target=RecordBlog,args=('python线程',))
threads.append(t1)
threads.append(t2)
if __name__ == '__main__':
for t in threads:
# t.setDaemon(True) # 注意:一定在start之前设置,被主进程带走
t.start()
# t.join() #
# t1.join()
# t1.setDaemon(True)
# t2.join()########考虑这三种join位置下的结果?
print ("all over %s" %ctime())
输出:
Begin listening to 水手. Sat Jun 11 12:43:11 2022
Begin recording the python线程! Sat Jun 11 12:43:11 2022
all over Sat Jun 11 12:43:11 2022
end recording the python线程! Sat Jun 11 12:43:16 2022
end listening to 水手. Sat Jun 11 12:43:19 2022
2,获取线程名,开启线程的方式一
import threading
import time
def sayhi(num): # 定义每个线程要运行的函数
print("running on number:%s" % num)
time.sleep(3)
if __name__ == '__main__':
t1 = threading.Thread(target = sayhi, args = (1,)) # 生成一个线程实例
t2 = threading.Thread(target = sayhi, args = (2,)) # 生成另一个线程实例
t1.start() # 启动线程
t2.start() # 启动另一个线程
print(t1.getName()) # 获取线程名
print(t2.getName())
输出:
running on number:1
running on number:2
Thread-1
Thread-2
3,开启线程的方式二
import threading
import time
class MyThread(threading.Thread):
def __init__(self, num):
threading.Thread.__init__(self)
self.num = num
def run(self): # 定义每个线程要运行的函数
print("running on number:%s" % self.num)
time.sleep(3)
if __name__ == '__main__':
t1 = MyThread(1)
t2 = MyThread(2)
t1.start()
t2.start()
print("ending......")
输出:
running on number:1
running on number:2
ending......
标签:__,结束,threading,开启,t1,print,线程,进程,import 来源: https://www.cnblogs.com/heris/p/16365750.html