我正在尝试设置两个函数的多线程。函数B的执行取决于函数A的完成,因此我想等到函数A的所有线程都完成后再运行函数B的线程。但是函数A不依赖于函数B,所以当函数A的线程B正在运行,我想开始运行函数A的线程。在这种情况下,函数B只需要1个线程,但是函数A可以有多个线程。
这是我最佳尝试的代码示例。以下代码在functionB
中创建了一个长度为20的functionB
列表,并进行了20次迭代。在这20次迭代中的每一次迭代中,functionA
经历了200次迭代,以使其成为自己的临时列表firstList
,functionB
用来在secondList
functionA
的那200次迭代中可以有多个工作程序。 functionB
一次只能有一个。在k
的一次迭代中,functionB
需要等待,直到functionA
的所有200次迭代都完成为止。但是在迭代k+1
时,functionA
应该继续进行下一个迭代,而不是在迭代functionB
时等待k
的迭代。
import threading
maxthreads = 4
sema1 = threading.Semaphore(value=maxthreads)
maxthreads = 1
sema2 = threading.Semaphore(value=maxthreads)
def functionA( i ):
sema1.acquire()
firstList.append( i*2 )
sema1.release()
def functionB( j ):
sema2.acquire()
secondList.append( j + sum(firstList) )
sema2.release()
secondList = []
for k in range(20):
firstList = []
for n in range(0, 200):
thread = threading.Thread(target=functionA,args=(n, ))
thread.start()
thread = threading.Thread(target=functionB,args=(m, ))
thread.start()
对于functionB
的每次迭代,如何设置线程,以使n
函数在所有FirstOne
的{{1}}个迭代线程都完成之后才能运行,
而且k
线程将在functionA
的下一次迭代中继续进行n
的下一次迭代,即使单个线程在{{1}处占用k+1
}尚未完成?由于不一定要在迭代functionB
进行k
,所以要让functionB
的线程在迭代k
开始任务。
还请注意,functionA
一次只能运行一个线程,而k+1
可以有多个线程。
编辑:
Dan D.在下面发布了一个解决方案,该解决方案阻止功能A和B都运行到另一个完成为止,但是我只需要阻止B一直运行到A完成,就可以不使用B来运行,我想到了Dan D解决方案的解决方案
functionB
因此,在函数b的线程末尾,我不进行线程连接,而是将其附加到a_threads。在调用所有函数b线程的末尾加入a_threads之后,我创建了一个新的空a_threads列表。
这是否可以满足我的要求?
答案 0 :(得分:0)
为此,在启动B线程之前先加入所有A线程。然后加入B线程,以使下一个A线程直到其结束才开始。
secondList = []
for k in range(20):
firstList = []
a_threads = []
for n in range(0, 200):
thread = threading.Thread(target=functionA,args=(n, ))
thread.start()
a_threads.append(thread)
for thread in a_threads:
thread.join()
thread = threading.Thread(target=functionB,args=(m, ))
thread.start()
thread.join()
为了允许A线程在B线程结束之前开始移动,从而转移了连接。
secondList = []
b_thread = None
for k in range(20):
firstList = []
a_threads = []
for n in range(0, 200):
thread = threading.Thread(target=functionA,args=(n, ))
thread.start()
a_threads.append(thread)
for thread in a_threads:
thread.join()
if b_thread is not None:
b_thread.join()
thread = threading.Thread(target=functionB,args=(m, ))
thread.start()
b_thread = thread
if b_thread is not None:
b_thread.join()