我正在嘗試簡化以下執行緒代碼:
import threading
def test1():
print("test1")
def test2():
print('test2')
thread1 = threading.Thread(target=test1)
thread2 = threading.Thread(target=test2)
thread1.start()
thread2.start()
thread1.join()
thread2.join()
因此,我想將下面這部分代碼簡化為:
# ...
thread1 = threading.Thread(target=test1)
thread2 = threading.Thread(target=test2)
thread1.start()
thread2.start()
thread1.join()
thread2.join()
類似于下面的一行代碼:
# ...
threading.Threads(test1, test2).start().join()
有沒有辦法做到這一點?如果不是一行代碼也沒關系,只要它更簡單。
uj5u.com熱心網友回復:
自己寫吧……
class Threads:
def __init__(self,*functions):
self._functions = functions
self._threads = []
def start(self):
for func in self._functions:
thread = threading.Thread(target=func)
self._threads.append(thread)
thread.start()
return self
def join(self):
for thread in self._threads:
thread.join()
用法:
Threads(test1, test2).start().join()
編輯:使用執行緒池更 Pythonic
from operator import methodcaller
from multiprocessing.pool import ThreadPool
caller = methodcaller("__call__")
with ThreadPool() as pool:
results = pool.map(caller, [test1, test2])
uj5u.com熱心網友回復:
import threading
threads_list = []
for i in range(thread_count)
thread = threading.Thread(target=target_func, args=(args,))
thread.start()
threads_list.append(thread)
uj5u.com熱心網友回復:
您可以重構函式,使它們是相同的函式但具有不同的輸入,例如
def test(s):
print(s)
然后,您可以使用更高級別的ThreadPoolapi。這通過不同的執行緒test使用串列中的每個元素呼叫該函式。['test1', 'test2']因此,您無需管理啟動或加入執行緒等細節。
from multiprocessing.pool import ThreadPool
with ThreadPool as pool:
results = pool.map(test, ['test1', 'test2'])
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/520355.html
標籤:Pythonpython-3.x多线程并发python-多线程
上一篇:如果沒有一致執行,則批處理
下一篇:ParallelOptions'MaxDegreeOfParallelism'屬性-為什么我可以指定比我的硬體更多的執行緒?
