join(等待某執行緒結束在繼續執行)
queue 儲存程序結果
執行緒鎖在cpython中存在gil,大家可以嘗試其他直譯器版本,可能就不會存在gil了
import threading
(threading.active_count())
#列印已啟用執行緒數
(threading.
enumerate()
)#列印所有執行緒資訊
(threading.current_thread())
#列印現在正在執行的執行緒
def
thread_job()
:#定義執行緒的函式
('this is a thread of %s'
% threading.current_thread())
defmain()
: thread = threading.thread(target=thread_job,
)#定義執行緒
thread.start(
)# 讓執行緒開始工作
if __name__ ==
'__main__'
: main(
)
t = threading.thread(target=job,args=
(data[i]
,q))
#target後面的函式名不加括號,args後面的是引數
def
t1_job()
:#執行緒一
("t1 start\n"
)for i in
range(10
(i)print
("t1 finish\n"
)def
t2_job()
:#執行緒二
("t2 start\n"
("t2 finish\n"
)thread_1 = threading.thread(target=t1_job, name=
't1'
)#定義執行緒1
thread_2 = threading.thread(target=t2_job, name=
't2'
)#定義執行緒2
thread_1.start(
)# 開啟t1
thread_1.join(
)#####重點,等待執行緒1結束在開始執行執行緒2
thread_2.start(
)# 開啟t2
from queue import queue
import threading
from queue import queue
defjob
(l,q)
:## 執行緒執行的函式
for i in
range
(len
(l))
: l[i]
= l[i]**2
q.put(l)
defmultithreading()
: q =queue(
)##定義佇列
threads =
data =[[
1,2,
3],[
3,4,
5],[
4,4,
4],[
5,5,
5]]for i in
range(4
):##開啟四個執行緒
t = threading.thread(target=job,args=
(data[i]
,q))
##此處也要把定義的q傳進去
t.start(
)for thread in threads:
## 等待四個執行緒全部結束
thread.join(
) results =
for _ in
range(4
):))
#從佇列中拿出資料
(results)
import threading
defjob1()
:global a,lock #定義使用全域性變數
lock.acquire(
)#鎖線程
for i in
range(10
):a+=
1print
('job1'
,a) lock.release(
)#釋放執行緒鎖
defjob2()
:global a,lock #定義使用全域性變數
lock.acquire(
)#鎖線程
for i in
range(10
):a+=
10print
('job2'
,a) lock.release(
)#釋放執行緒鎖
lock=threading.lock(
)#定義程序鎖(全域性變數)a=0
t1=threading.thread(target=job1)
t2=threading.thread(target=job2)
t1.start(
)t2.start(
)t1.join(
)t2.join(
)
Python基礎 多執行緒
多執行緒在程式開發過程中特別重要,我們往往把一些耗時的操作在子執行緒中執行,這就是所謂的多執行緒了。在c 11中,寫了一些關於多執行緒的部落格。python也不例外,當然也要有多執行緒了。python提供了兩個模組來實現多執行緒thread 和threading thread 有一些缺點,在thre...
Python基礎 多執行緒
多工可以由多程序完成,也可以由乙個程序內的多執行緒完成。我們前面提到了程序是由若干執行緒組成的,乙個程序至少有乙個執行緒。由於執行緒是作業系統直接支援的執行單元,因此,高階語言通常都內建多執行緒的支援,python也不例外,並且,python的執行緒是真正的posix thread,而不是模擬出來的...
Python多執行緒基礎學習
python多執行緒用法 1.函式式 呼叫thread模組的start new thread 方法來建立執行緒,例如 thread.start new thread function,args args是函式的引數列表,在python裡用元組表示,如 args1 args2 注意這裡引數必須存在,就...