python之多執行緒(學習)

2021-10-24 16:17:43 字數 2956 閱讀 5478

執行緒分為:

核心執行緒:由作業系統核心建立和撤銷

使用者執行緒:不需要核心支援而在使用者程式中實現的執行緒

python3 執行緒中常用的兩個模組:

_thread和threading(推薦使用)
python中使用執行緒有兩種方式:函式或者用類來包裝執行緒物件
函式式:

#呼叫模組

import _thread

import time

#為執行緒定義乙個函式

defprint_time

(th,delay)

: count =

0while count <5:

#延時 time.sleep(delay)

count +=

1#轉換時間戳

print

("%s:%s"

%(th,time.ctime(time.time())

))#建立兩個執行緒

try:

_thread.start_new_thread(print_time,

("thread1",2

,)) _thread.start_new_thread(print_time,

("thread2",4

,))except

:print

("無法啟動"

)#一直迴圈

while1:

pass

使用 threading 模組建立執行緒:

#呼叫模組

import threading

import time

exitflag =

0#宣告了個類

class

mythread

(threading.thread)

:def

__init__

(self, threadid, name, counter)

: threading.thread.__init__(self)

self.threadid = threadid

self.name = name

self.counter = counter

defrun(self)

:print

("開始執行緒:"

+ self.name)

print_time(self.name, self.counter,5)

print

("退出執行緒:"

+ self.name)

defprint_time

(threadname, delay, counter)

:while counter:

if exitflag:

threadname.exit(

) time.sleep(delay)

print

("%s: %s"

%(threadname, time.ctime(time.time())

))counter -=

1# 建立新執行緒

thread1 = mythread(1,

"thread-1",1

)thread2 = mythread(2,

"thread-2",2

)# 開啟新執行緒

thread1.start(

)thread2.start(

)thread1.join(

)thread2.join(

)print

("退出主線程"

)

執行緒同步:

import threading

import time

class

mythread

(threading.thread)

:def

__init__

(self, threadid, name, counter)

: threading.thread.__init__(self)

self.threadid = threadid

self.name = name

self.counter = counter

defrun(self)

:print

("開啟執行緒: "

+ self.name)

# 獲取鎖,用於執行緒同步

threadlock.acquire(

) print_time(self.name, self.counter,3)

# 釋放鎖,開啟下乙個執行緒

threadlock.release(

)def

print_time

(threadname, delay, counter)

:while counter:

time.sleep(delay)

print

("%s: %s"

%(threadname, time.ctime(time.time())

))counter -=

1threadlock = threading.lock(

)threads =

# 建立新執行緒

thread1 = mythread(1,

"thread-1",1

)thread2 = mythread(2,

"thread-2",2

)# 開啟新執行緒

thread1.start(

)thread2.start(

)# 新增執行緒到執行緒列表

# 等待所有執行緒完成

for t in threads:

t.join(

)print

("退出主線程"

)

python學習二之多執行緒

python學習二之多執行緒 1.執行緒 多工可以由多程序完成,也可以由乙個程序內的多執行緒完成。我們前面提到了程序是由若干執行緒組成的,乙個程序至少有乙個執行緒。由於執行緒是作業系統直接支援的執行單元,因此,高階語言通常都內建多執行緒的支援,python也不例外,並且,python的執行緒是真正的...

Python之多執行緒

1 呼叫thread模組中的start new thread 函式來產生新執行緒 thread.start new thread function,args kwargs function 執行緒函式。args 傳遞給執行緒函式的引數,他必須是個tuple型別。kwargs 可選引數。2 使用thr...

python之多執行緒

學習了一下多執行緒 用到爬蟲裡面簡直爽歪歪呀 定義就很簡單,為了實現高併發,能夠同時在乙個指令碼下執行多個程式,節約時間 新增執行緒用到的 import threading as td def sum num1,num2 sum num1 num2 print sss sum def divided...