1. 程式人生 > >python創建進程的兩種方式

python創建進程的兩種方式

lis time self. ssi 相關 進程創建 int RoCE target

線程內的任務不會同時執行,可以解決的方法是在每個進程裏面執行一個線程,可以實現。(GIL的限制)

multiprocessing管理進程的包,threading.Thread用來管理線程

進程可以解決並發,但是相關的消息無法交互,需要借助別的例如Pipe和Queue(但是在使用的時候仍有資源的消耗)

進程的創建方式一:函數式

from multiprocessing import Process
# 導入創建進程需要的包

import  time

def f(name):
    time.sleep(1)
    # 進程休眠一秒
    print(hello,name,time.ctime())
if __name__==__main__: p_list=[] for i in range(3): p=Process(target=f,args=(alvin,)) p_list.append(p) p.start() for i in p_list: p.join() print(end) 結果如下 hello alvin Sun Feb 10 12:32:54 2019 hello alvin Sun Feb 10 12:32:54 2019 hello alvin Sun Feb
10 12:32:54 2019 end

進程創建方式二: 類

from  multiprocessing import Process
import time
class MyProcess(Process):
    def __init__(self,name):
        super(MyProcess,self).__init__()
        self.name=name
    #     繼承父方法的構造器
    def run(self):
        time.sleep(1)
        print(hello,self.name,time.ctime())

if __name__==__main__: p_list=[] for i in range(3): p=MyProcess(jiao) p.start() p_list.append(p) for p in p_list: p.join() print(end)

python創建進程的兩種方式