1. 程式人生 > 遊戲 >在精釀世界尋覓經典 《老鐵,我啤酒呢?》官中上線

在精釀世界尋覓經典 《老鐵,我啤酒呢?》官中上線

程序:一個電腦可以同時八個人工作,開啟八個程序

執行緒:同一個時間點上,只有一個執行緒在工作,執行緒在程序之內

程序之間資源不共享,執行緒之間資源共享

併發(Concurrent),在作業系統中,是指一個時間段中有幾個程式都處於已啟動執行到執行完畢之間,且這幾個程式都是在同一個處理機上執行。

並行(Parallel),當系統有一個以上CPU時,當一個CPU執行一個程序時,另一個CPU可以執行另一個程序,兩個程序互不搶佔CPU資源,可以同時進行,這種方式我們稱之為並行(Parallel)。

其實決定並行的因素不是CPU的數量,而是CPU的核心數量,比如一個CPU多個核也可以並行。

多工實現有3種方式:

多程序模式

多執行緒模式

多程序多執行緒模式

multiprocessing多程序

os.getpid():獲取當前程序id

多程序必須定義:

def run_proc(name):
    print('Run child process %s (%s)...' % (name, os.getpid()))

if __name__=='__main__':
    print('Parent process %s.' % os.getpid())
    p = Process(target=run_proc, args=('test',))#生成一個程序
    print('Child process will start.
') p.start()#開啟程序 p.join()#等待程序結束 print('Child process end.')

Pool程序池,暫時存放程序的地方:它可以進行提速

from multiprocessing import Pool
import os, time, random

def long_time_task(name):
    print('Run task %s (%s)...' % (name, os.getpid()))
    start = time.time()
    time.sleep(random.random() * 3)
    end 
= time.time() print('Task %s runs %0.2f seconds.' % (name, (end - start))) if __name__=='__main__': print('Parent process %s.' % os.getpid()) p = Pool(4)#4個任務 for i in range(5):#5個程序 p.apply_async(long_time_task, args=(i,)) print('Waiting for all subprocesses done...') p.close() p.join() print('All subprocesses done.')

多程序中子程序報錯是不會顯示的,它會顯示主程序完事。

join:結束

terminate:強行結束

from multiprocessing import Process, Queue
import os, time, random

# 寫資料程序執行的程式碼:
def write(q):
    print('Process to write: %s' % os.getpid())
    for value in ['A', 'B', 'C']:
        print('Put %s to queue...' % value)
        q.put(value)
        time.sleep(random.random())

# 讀資料程序執行的程式碼:
def read(q):
    print('Process to read: %s' % os.getpid())
    while True:
        value = q.get(True)
        print('Get %s from queue.' % value)

if __name__=='__main__':
    # 父程序建立Queue,並傳給各個子程序:
    q = Queue()
    pw = Process(target=write, args=(q,))
    pr = Process(target=read, args=(q,))
    # 啟動子程序pw,寫入:
    pw.start()
    # 啟動子程序pr,讀取:
    pr.start()
    # 等待pw結束:
    pw.join()
    # pr程序裡是死迴圈,無法等待其結束,只能強行終止:
    pr.terminate()

執行緒

多執行緒寫法:

import threading