目錄1、
2、lock
# encoding: utf-8
import threading
import time
from queue import queue
def thread_1_job():
print("thread-1 start\n")
for i in range(10):
time.sleep(0.3)
print("thread-1 finished\n")
def thread_2_job():
print("thread-2 start\n")
for c in "abcdefg":
time.sleep(0.3)
print("thread-2 finished\n")
def queue_job(list,q):
for i in range(len(list)):
list[i] = list[i] **2
q.put(list)
"""threading多執行緒的常用方法"""
def main_1():
# 新增乙個執行緒,並新增執行緒所需函式
thread = threading.thread(target=thread_1_job)
# 執行執行緒
thread.start()
# 當前啟用的執行緒數
print(threading.active_count())
# 當前啟用執行緒的詳細資訊
print(threading.enumerate())
# 正在執行的執行緒詳細資訊
print(threading.current_thread())
"""join主線程等待執行緒執行完畢"""
def main_join():
# 新增乙個執行緒,並新增執行緒所需函式
# target= thread_job()不能帶括號
thread_1 = threading.thread(target=thread_1_job,name='thread-1')
thread_2 = threading.thread(target=thread_2_job,name="thread-2")
thread_1.start()
thread_2.start()
# 等待執行緒執行結束後在去繼續向後執行
thread_1.join()
thread_2.join()
print("all threads is done !!")
"""queue多執行緒分批處理資料"""
def main_queue(data):
# 存放執行緒的返回值
q = queue()
threads =
#for i in range(4):
# queue_job沒有括號,args是向執行緒傳遞的引數
t = threading.thread(target=queue_job,args=(data[i],q))
t.start()
for t in threads:
t.join()
result =
for _ in range(4):
# 該方法只能拿出乙個值,並且有序
r = q.get()
print(result)
if __name__ == '__main__':
# main_1()
# main_join()
data = [[1,2,3],[3,4,5],[4,4,4],[5,5,5]]
main_queue(data)
# encoding: utf-8
import threading
import time
from queue import queue
"""處理共享變數"""
def job1():
global a,lock
# 開始加鎖
lock.acquire()
for i in range(2):
a += 1
print("job_1 num = %s " % a)
# 釋放鎖
lock.release()
def job2():
global a,lock
# 開始加鎖
lock.acquire()
for i in range(2):
a += 10
print("job_2 num =%s " % a)
# 釋放鎖
lock.release()
if __name__ == '__main__':
"""實現將job1 列印完後再列印 job2"""
a = 0 # 全域性變數
lock = threading.lock()
t1 = threading.thread(target=job1)
t2 = threading.thread(target=job2)
t1.start()
t2.start()
t1.join()
t2.join()
Python threading(執行緒模組)
建立和使用方式基本和程序一致。有關執行緒的文字講述,請見 計算機 程序 執行緒 協程 import time from threading import thread,current thread,enumerate,active count def func i1,i2 i i1 i2 time....
簡述python(threading)多執行緒
一.概述 import threading 呼叫 t1 threading.thread target function args join 在子執行緒完成執行之前,這個子執行緒的父執行緒將一直被阻塞。setdaemon true 將執行緒宣告為守護執行緒,必須在start 方法呼叫之前設定,如果不...
python threading關於鎖的內容
鎖 import threading,time defaddnum global num lock.acquire 獲取鎖 temp num time.sleep 0.01 print ok num temp 1lock.release 釋放鎖 鎖保證執行緒沒有執行完cpu不會執行別的執行緒 num...