這篇文章我是根據【莫煩Python】Threading 學會多線程 Python的視頻做的學習記錄。
莫煩Python好帥好可愛哈哈哈。
import threading
def thread_job():
print('This is an added Thread, number id %s' % threading.current_thread())
def main():
added_thread = threading.Thread(target=thread_job) # 創建線程
added_thread.start() # 啟動線程
if __name__ == '__main__':
main()
首先思考幾個問題:
import threading
import time
def thread_job():
print('T1 start')
for i in range(10):
time.sleep(0.1)
print('T1 finish')
def t2_job():
print('T2 start')
print('T2 finish')
def main():
added_thread = threading.Thread(target=thread_job, name='T1')
thread2 = threading.Thread(target=t2_job)
added_thread.start()
thread2.start()
added_thread.join()
thread2.join()
print('all down!')
if __name__ == '__main__':
main()
可以往線程裏面傳遞參數,但是線程不能有返回值。
以下實例的目的是將data列錶中的值全部平方:
import threading
import time
from queue import Queue
# 需要修改的列錶數據
data = [[1, 2, 3], [3, 4, 5], [4, 4, 4], [5, 5, 5]]
# 定義一個功能函數,將列錶中的值平方
def job(l):
for i in range(len(l)):
l[i] = l[i]**2
return l
# 如果不用多線程,用以下方式實現
def no_threading():
result = []
for d in data:
r = job(d)
result.append(r)
print(result)
def job2(l, q):
for i in range(len(l)):
l[i] = l[i]**2
q.put(l)
def multithreading():
q = Queue()
threads = []
# 啟動線程
for i in range(4):
t = threading.Thread(target=job2, args=(data[i], q))
t.start()
threads.append(t)
# 回收線程
for thread in threads:
thread.join()
# 獲取數據
results = []
for _ in range(4):
results.append(q.get())
print(results)
if __name__ == '__main__':
# no_threading()
multithreading()
import threading
def job1():
global A, lock
lock.acquire()
for i in range(10):
A += 1
print('job1', A)
lock.release()
def job2():
global A, lock
lock.acquire()
for i in range(10):
A += 10
print('job2', A)
lock.release()
if __name__ == '__main__':
A = 0
lock = threading.Lock()
t1 = threading.Thread(target=job1)
t2 = threading.Thread(target=job2)
t1.start()
t2.start()
t1.join()
t2.join()