进程和线程的标识,守护模式
进程pid与线程ident
进程:
import multiprocessing as mp import time def fun(): time.sleep(2) process=mp.Process(target=fun) print("启动进程前:",process.pid) process.start() print("启动进程后:",process.pid) >>>启动进程前: None 启动进程后: 26784
线程:
import threading as th import time def fun(): time.sleep(2) thread=th.Thread(target=fun) print("启动进程前:",thread.ident) thread.start() print("启动进程后:",thread.ident) >>>启动进程前: None 启动进程后: -1262957760
进程名和线程名
import threading as th thread=th.Thread(name="joe-one") print(thread) print(thread.name) >>>><Thread(joe-one, initial)> joe-one
import multiprocessing as mp process=mp.Process(name="joe-one") print(process) print(process.name) >>>><Process(joe-one, initial)> joe-one
当前进程和当前线程
import multiprocessing as mp import time def fun(): time.sleep(2) print(mp.current_process()) process=mp.Process(target=fun,name='one') process2=mp.Process(name='two') process.start() print(mp.current_process()) >>>><_MainProcess(MainProcess, started)> <Process(one, started)>
等待进程或线程结束
import multiprocessing as mp import time,datetime def fun(): time.sleep(2) print(datetime.datetime.now()) process=mp.Process(target=fun,name='one') process.start() process.join() time.sleep(5) print(datetime.datetime.now()) >>>>2018-09-19 11:25:16.476846 2018-09-19 11:25:23.491335
进程和线程的生存状态
import multiprocessing as mp import time def fun(): time.sleep(2) process=mp.Process(target=fun,name='one') print(process) print(process.is_alive()) process.start() print(process) print(process.is_alive()) >>>><Process(one, initial)> False <Process(one, started)> True
中止进程
import multiprocessing as mp import time def fun(): print("进程开启》》》") time.sleep(5) print("进程结束》》》") process=mp.Process(target=fun,name='one') process.start() time.sleep(2) process.terminate() >>>>进程开启》》》
注意:线程不能被终止,只能等待其运行结束!
守护模式
下面的程序中,当主进程运行结束后设置成守护模式的子进程会在2s后被“杀死”,而不是等待其执行结束,就像很多应用一样,主界面关掉其他子界面都会关掉。
import multiprocessing as mp import time def fun(): print("进程开启》》》") time.sleep(5) print("进程结束》》》") process=mp.Process(target=fun,daemon=True) process.start() time.sleep(2) >>>进程开启》》》
多进程实现并发服务端
import multiprocessing import socket server=socket.socket() server.bind(('0.0.0.0',9969)) server.listen() def work(conn): while True: data=conn.recv(1024) if data==b'': conn.close() break else: print(data) conn.send(data) while True: conn,addr=server.accept() multiprocessing.Process(target=work,args=(conn,)).start()
多线程实现并发服务端
import threading import socket server = socket.socket() server.bind(('127.0.0.1', 9969)) server.listen() #子线程只处理消息 def worker(conn): while True: data = conn.recv(1204) if data == b'': conn.close() break else: print(data) conn.send(data) #主线程 while True: conn, addr = server.accept() # 线程去处理消息 thread = threading.Thread(target=worker, args=(conn,) ).start()
客户端
import socket client=socket.socket() client.connect(('127.0.0.1',9969)) while True: data=input("请输入要发送的数据:") data=data.encode() client.send(data) print("接收到的数据是:",client.recv(1024).decode())