[英]An error when opening multiple webdrivers in multi-thread processing in python
[英]Python: How to Multi-Thread a Function that Returns Multiple Values
我有一個包含兩個函數的程序,每個函數返回2個值。 一切運行正常,無需任何並行化。 但是,我希望實現的是在每個函數各自的線程/進程中運行它們。 程序在並行化之前是這樣的:
def func1():
x = 2
y =5
return x,y
def func2():
a = 4
b = 3
return a,b
func1ResultX , func1ResultY = func1()
func2ResultA , funct2ResultB = func2()
我知道我可以使用thread
, threading
或multiprocessing
實現此目的。 但是尚不清楚如何構造程序以返回結果或返回多個值。 我的初步努力產生了以下結果
使用thread
function1ResultX, function1ResultY = thread.start_new_thread(func1)
function2ResultA, function2ResultB = thread.start_new_thread(func2)
結果: TypeError: 'int' object is not iterable
使用multiprocessing
function1ResultX , function1Resulty = multiprocessing.Process(target=func1)
function2ResultA, function2ResultB = thread.start_new_thread(func2)
結果: TypeError: 'Process' object is not iterable
使用threading
我看到該示例類似於以下內容:
t1 = threading.Thread(target=someFunc)
t1.start()
t1.join()
但是我不知道如何修改示例以適合返回兩個值的函數,也不知道如何僅返回一個值。
我嘗試將函數減少為僅返回一個值,如下所示:
def func1():
MyNewList = [2,5]
return MyNewList
並結合使用threading
模塊的方法:
MyNewList = threading.Thread(target=func1)
MyNewList.start()
MyNewList.join()
print MyNewList[0]
print MyNewList[1]
雖然我期望輸出是2
和5
,但是我得到了錯誤:
TypeError: 'Thread' object does not support indexing
簡而言之,我的問題是:哪種並行化方法/模塊最適合我的情況,我應該如何構造我的代碼以適應它? 也歡迎就我的概念性誤解提供任何反饋。 先感謝您。
您可能需要稍微修改一下功能以使用Queue
來獲得結果。
import threading, Queue
def func1(queue):
x = 2
y = 5
queue.put((x, y))
queue = Queue.Queue()
new_thread = threading.Thread(target=func1, args=(queue, ))
new_thread.start()
new_thread.join()
x, y = queue.get()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.