python學習-----9.5----進程相關

開啓進程的兩種方式json

from multiprocessing import Process
import  time

def task(name):
    print('%s is running'%name)
    time.sleep(3)
    print('%s is done' %name)


#在windows系統上,開啓子進程的操做必須放到if __name__ =='main'的子代碼塊中
if __name__ == '__main__':
    p=Process(target=task,args=('egon',))
    p.start()#只是向操做系統發送一個開啓子進程的序號
    print('')
方式一
from multiprocessing import Process
import time


class Myprocess(Process):
    def __init__(self,name):
        super().__init__()
        self.name=name

    def run(self):
        print('%s is running' %self.name)
        time.sleep(3)
        print('%s is done' %self.name)

if __name__ == '__main__':
    p=Myprocess('egon')
    p.start()
    print('')
方式二

 

join:讓主進程在原地等待,等待子進程運行完畢,不會影響子進程的執行windows

 

from multiprocessing import Process
import time


def task(name,n):
    print('%s is running'%name)
    time.sleep(n)
    print('%s is done' %name)

if __name__ == '__main__':
    start=time.time()
    p_l=[]
    for i in range(1,4):
        p=Process(target=task,args=('子%s' %i,i))
        p_l.append(p)
        p.start()

    for p in p_l:
        p.join()
    print('',(time.time()-start))
View Code

 

 

 

守護進程:本質就是一個子進程,該子進程的生命週期<=被守護進程的生命週期安全

 

from multiprocessing import  Process
import time


def task(name):
    print('%s is run ning' %name)
    time.sleep(3)
    print('%s is done' %name)

if __name__ == '__main__':
    p=Process(target=task,args=('lqx',))
    p.daemon = True
    p.start()
    time.sleep(4)

    print('%s is done' %('egon'))

 

 

 

 

 

進程對象其餘相關屬性或方法網絡

 

1 group參數未使用,值始終爲None
2 
3 target表示調用對象,即子進程要執行的任務
4 
5 args表示調用對象的位置參數元組,args=(1,2,'egon',)
6 
7 kwargs表示調用對象的字典,kwargs={'name':'egon','age':18}
8 
9 name爲子進程的名稱
參數介紹

 

 1 p.start():啓動進程,並調用該子進程中的p.run() 
 2 p.run():進程啓動時運行的方法,正是它去調用target指定的函數,咱們自定義類的類中必定要實現該方法  
 3 
 4 p.terminate():強制終止進程p,不會進行任何清理操做,若是p建立了子進程,該子進程就成了殭屍進程,使用該方法須要特別當心這種狀況。若是p還保存了一個鎖那麼也將不會被釋放,進而致使死鎖
 5 p.is_alive():若是p仍然運行,返回True
 6 
 7 p.join([timeout]):主線程等待p終止(強調:是主線程處於等的狀態,而p是處於運行的狀態)。timeout是可選的超時時間,須要強調的是,p.join只能join住start開啓的進程,而不能join住run開啓的進程  
方法介紹
1 p.daemon:默認值爲False,若是設爲True,表明p爲後臺運行的守護進程,當p的父進程終止時,p也隨之終止,而且設定爲True後,p不能建立本身的新進程,必須在p.start()以前設置
2 
3 p.name:進程的名稱
4 
5 p.pid:進程的pid
6 
7 p.exitcode:進程在運行時爲None、若是爲–N,表示被信號N結束(瞭解便可)
8 
9 p.authkey:進程的身份驗證鍵,默認是由os.urandom()隨機生成的32字符的字符串。這個鍵的用途是爲涉及網絡鏈接的底層進程間通訊提供安全性,這類鏈接只有在具備相同的身份驗證鍵時才能成功(瞭解便可)
屬性介紹

 

 

 

互斥鎖app

  進程之間數據不共享,可是共享同一套文件系統,因此訪問同一個文件,或同一個打印終端,是沒有問題的,而共享帶來的是競爭,競爭帶來的結果就是錯亂,如何控制,就是加鎖處理dom

 

#加鎖能夠保證多個進程修改同一塊數據時,同一時間只能有一個任務能夠進行修改,即串行的修改,沒錯,速度是慢了,但犧牲了速度卻保證了數據安全。
雖然能夠用文件共享數據實現進程間通訊,但問題是:
1.效率低(共享數據基於文件,而文件是硬盤上的數據)
2.須要本身加鎖處理
import json
import time,random
from multiprocessing import Process,Lock

def search(name):
    with open('db.json','rt',encoding='utf-8')as f:
        dic=json.load(f)
    time.sleep(1)
    print('%s 查看到餘票爲%s'%(name,dic['count']))

def get(name):
    with open('db.json','rt',encoding='utf-8')as f:
        dic=json.load(f)
    if dic['count']>0:
        dic['count']-=1
        time.sleep(random.randint(1,3))
        with open('db.json','wt',encoding='utf-8')as f:
            json.dump(dic,f)
            print('%s購票成功'%name)
    else:
        print('%s 查看到沒有票了'%name)

def task(name,mutex):
    search(name)
    mutex.acquire()
    get(name)
    mutex.release()

if __name__ == '__main__':
    mutex=Lock()
    for i in range(10):
        p=Process(target=task,args=('路人%s'%i,mutex))
        p.start()
模擬搶票
相關文章
相關標籤/搜索