python+selenium自動化測試-10進程與線程

進程,是計算機中程序關於某數據集合上的一次運行活動,是系統進行資源分配和調度的基本單位,是操作系統結構的基礎。線程是程序執行流的最小單位,是進程的一個實體,是被系統獨立調度和分派的基本單位。一個進程可以包含多個線程,進程和線程是一對多的關係。線程自己不擁有系統資源,在單個程序中同時運行多個線程完成不同的工作,稱爲多線程。線程和進程的區別在於,子進程和父進程有不同的代碼和數據空間,而多個線程則共享數據空間,每個線程有自己的執行堆棧和程序計算器爲其執行上下文。

關於CPU、進程和線程,可以用一個比喻形象來描述:計算機核心是CPU,像一個工廠,進程是工廠裏面的車間,負責完成某一項任務。工廠資源有限,只能在某個時刻支撐某個車間運轉,所以,CPU在一段時間內是不斷切換進程工作的。一個車間內有很多工人,相當於線程,共享着車間的空間和資源,每個線程都爲了同一個任務而工作。

下面將通過代碼介紹線程、進程的應用:

1、單線程(執行有先後)

from time import ctime,sleep

#定義說和寫
def talk():
    print("we talk:%r,%r" %(content,ctime()))
    sleep(2)

def write():
    print("we write:%r,%r" % (content, ctime()))
    sleep(2)

if __name__=='__main__':
    talk()
    write()

 

2、多線程(併發進行)

from time import ctime,sleep
import threading

#定義說和寫
def talk(content,loop):
    for i in range(loop):
        print("we talk:%r,%r" %(content,ctime()))
        sleep(2)

def write(content, loop):
    for i in range(loop):
        print("we write:%r,%r" % (content, ctime()))
        sleep(2)

#定義和裝載說和寫的線程
threads=[]
t1=threading.Thread(target=talk,args=('hello',2))
threads.append(t1)

t2=threading.Thread(target=write,args=('hi',2))
threads.append(t2)

#執行多線程
if __name__=='__main__':
    for t in threads:
        t.start()
    for t in threads:
        t.join()

3、多進程

import multiprocessing

from time import ctime,sleep

 

#定義說和寫
def talk(content,loop):
    for i in range(loop):
        print("we talk:%r,%r" %(content,ctime()))
        sleep(2)

def write(content, loop):
    for i in range(loop):
        print("we write:%r,%r" % (content, ctime()))
        sleep(2)

 

process=[]

p1=mutiprocessing.Process(target=talk,args=('hello,2'))

process.append(p1)

p2=mutiprocessing.Process(target=write,args=('hi,2'))

process.append(p2)

 

#執行多線程
if __name__=='__main__':
    for t in process:
        t.start()
    for t in process:
        t.join()

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章