多執行緒 新增執行緒Thread

2021-10-03 14:25:41 字數 2355 閱讀 2172

今天我們來學習threading模組的一些基本操作,如獲取執行緒數,新增執行緒等。首先別忘了匯入模組:

import threading
獲取已啟用的執行緒數

import threading

defmain()

:print

(threading.active_count())

if __name__ ==

"__main__"

: main(

)#輸出

1

檢視所有執行緒資訊

import threading

defmain()

:print

(threading.

enumerate()

)if __name__ ==

"__main__"

: main(

)#輸出

[<_mainthread(mainthread, started 4790924736

)>

]

顯示當前執行緒

import threading

defmain()

:#print(threading.active_count())

#print(threading.enumerate())

print

("currnet thread :"

,threading.current_thread())

if __name__ ==

"__main__"

: main(

)

新增執行緒,threading.thread()接收引數target代表這個執行緒要完成的任務,需自行定義

import threading

defthread_job()

:#python模組中的乙個功能

print

('this is a thread of %s'

% threading.current_thread())

defmain()

: thread = threading.thread(target=thread_job,

)# 定義執行緒,並且把功能傳進去

thread.start(

)# 讓執行緒開始工作

#print(threading.active_count())

print

(threading.

enumerate()

)#print("currnet thread :",threading.current_thread())

if __name__ ==

'__main__'

: main(

)#輸出

this is an added thread,number is

>

[<_mainthread(mainthread, started 4748305856

)>

,1, started 123145447149568

)>

]

import threading

defthread_job()

:print

("this is an added thread,number is %s"

% threading.current_thread)

defmain()

: added_thread = threading.thread(target = thread_job)

added_thread.start(

)print

(threading.active_count())

print

(threading.

enumerate()

)print

("currnet thread :"

,threading.current_thread())

if __name__ ==

"__main__"

: main(

)

輸出

this is an added thread,number is

>2[

<_mainthread(mainthread, started 4573492672

)>

]currnet thread :

<_mainthread(mainthread, started 4573492672

)>

Python多執行緒(1)新增執行緒

基本指令 新增執行緒 import threading defthread job print this is an added thread,number is s n threading.current thread defmain added threading threading.threa...

Python多執行緒開發1 新增執行緒

匯入執行緒模組 import threading獲取已啟用的執行緒數 threading.active count 2檢視所有執行緒資訊 threading.enumerate mainthread mainthread,started 140736011932608 started daemon ...

多執行緒 Thread

如果從另外乙個執行緒操作windows窗體上的控制項,就會與主線程產生競爭,造成不可預料的後果,甚至死鎖。因此,windows gui程式設計有乙個規則 只能通過建立控制項的執行緒來操作控制項的資料!實現方法 要從執行緒外操作windows控制項,那麼就要使用invoke或begininvoke方法...