python 併發程式設計入門

2021-09-08 13:00:58 字數 2738 閱讀 6355

在unix/linux下,為我們提供了類似c中標頭檔案裡的的fork()函式的介面,這個函式位於os模組中,相同與c中類似,對於父程序fork()呼叫返回子程序id,對於子程序返回0

import os, time

pid = os.fork()

if pid == 0:

while true:

print 'child process'

time.sleep(1)

else:

while true:

print 'parent process'

time.sleep(3)

考慮到windows並沒有這個呼叫,python為我們提供了跨平台的版本號。這就是multiprocessing模組。通過multiprocessing模組中的process類可實現跨平台的多程序。使用方法很easy

#coding:utf-8

from multiprocessing import process

import os, time

def handler(args):

print 'process parameter is %s' % args

while true:

print 'child process'

time.sleep(1)

if __name__=='__main__':

print 'parent process is %d' % os.getpid()

child_proc = process(target = handler, args=('test parameter',)) #指定子程序開始執行的函式

child_proc.start()

while true:

print 'parent process'

time.sleep(3)

注意:若不加if __name__=='__main__'。子程序啟動後會將模組內的**再執行一遍。為避免不必要的錯誤,應該加上它

python為了更方便的使用多程序還提供了程序池pool, 位於multiprocessing模組中,程序池用於對於併發響應要求較高的條件中,預先分配程序,節省了處理過程中fork的開銷

關於很多其它程序池的內容可參考   中的tcp預先派生子程序server

#coding:utf-8

from multiprocessing import pool

import os, time, random

def handler(proc_args):

print proc_args

if __name__ == '__main__':

pool = pool(4) #設定程序池中的程序數

for loop in range(4):

pool.close() #不在往程序池中加入程序 pool.join() #等待全部子程序結束 print 'all child processes done'

python中對於多執行緒提供了thread和threading模組, threading對thread進行了封裝,更易用。python官網的描寫敘述例如以下

this module provides low-level primitives for working with multiple threads (also called light-weight processes or tasks) — multiple threads of control sharing their global data space. for synchronization, ****** locks (also called mutexes or binary semaphores) are provided. the threading module provides an easier to use and higher-level threading api built on top of this module

呼叫thread模組中的start_new_thread()函式來產生新執行緒

import thread

def thread_handler(args):

print args

if __name__ == '__main__':

thread.start_new_thread(thread_handler, ('test parameter',))

while true:

pass

將執行緒函式傳入並建立thread例項。然後呼叫start()建立執行緒並執行

import threading

def thread_handler(args):

print args

if __name__ == '__main__':

th1 = threading.thread(target=thread_handler, args=('test parameter 1',))

th2 = threading.thread(target=thread_handler, args=('test parameter 2',))

th1.start()

th2.start()

th1.join()

th2.join()

print 'all threads ended'

Python 併發程式設計

1.程序 執行緒 協程基本概念,建立 使用 2.協程的應用 生成器 第三方模組 3.併發的實踐 程式執行起來之後建立的乙個程序。建立程序已經學過使用multiprocessing.process類建立 1 multiprocessing.process 指定target引數,建立物件 2 繼承mul...

python併發程式設計 程序,併發

1.程序是乙個正在執行的程式,或者說是程式執行的過程,程序是個抽象概念 程序起源於作業系統,是作業系統最核心的概念,作業系統所有其他的概念都是圍繞程序展開 研究程序最底層就是在研究作業系統底層 2.序列 程序 乙個任務完完整整的執行完畢後,在執行下乙個任務 3.併發 程序 看起來多個任務是同時執行即...

python併發程式設計調優 python併發程式設計

併發程式設計是我們程式設計中常用的優化程式效能的手段,能提高cpu的使用率。一般使用是多執行緒,多程序,協程 一 python的全域性解釋鎖gil 我們目前跑的python程式大多數都是在cpython上執行的。cpython是有乙個全域性解釋鎖,具體什麼意思,可以兩個方面理解 在同一時刻,只能執行...