在功能A的线程完成之前,功能B的多线程线程不会启动,但是功能A的线程不会等待功能B

时间:2019-06-26 14:58:31

标签: python multithreading

我正在尝试设置两个函数的多线程。函数B的执行取决于函数A的完成,因此我想等到函数A的所有线程都完成后再运行函数B的线程。但是函数A不依赖于函数B,所以当函数A的线程B正在运行,我想开始运行函数A的线程。在这种情况下,函数B只需要1个线程,但是函数A可以有多个线程。

这是我最佳尝试的代码示例。以下代码在functionB中创建了一个长度为20的functionB列表,并进行了20次迭代。在这20次迭代中的每一次迭代中,functionA经历了200次迭代,以使其成为自己的临时列表firstListfunctionB用来在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列表。

这是否可以满足我的要求?

1 个答案:

答案 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()