多线程条件,在第二次迭代时启动线程?

时间:2019-04-04 17:29:58

标签: python multithreading

[挑战]:

我有两个线程,第一个是 some_signal ,第二个是 post_proccesing

对于第一次迭代,我想在 some_signal 之后运行 post_proccesing

在第一次迭代之后。 我想启动 post_proccesing 线程,因此 post_proccesing 将使用上一个循环中的 some_signal 数据。

[伪代码]:

  • 第一次迭代:
    1. some_signal
    2. post_proccesing
  • 第二次迭代:

    1. 开始踏步

    2. some_signal和post_proccesing [some_signal-1]

[我的尝试]:

我尝试使用以下方式实现它,但是我不确定是否正确完成了

import threading

def some_signal():
    print threading.currentThread().getName(), 'Get signal'

def post_proccesing():
    print threading.currentThread().getName(), 'Process the signa;'

t = threading.Thread(name='post_proccesing', target=post_proccesing)
w = threading.Thread(name='some_signal', target=some_signal)

flag = 0;
for i in range(5):
    t = threading.Thread(target=some_signal) # use default name

    if flag == 0:
        some_signal() # use default name
        flag  = flag + 1;
    else:
        w = threading.Thread(target=post_proccesing) # use default name
    w.start()
    t.start()

1 个答案:

答案 0 :(得分:1)

在我看来,您可以基于i(您的迭代计数)实现逻辑。也许这样的事情适合您(我不确定您对flag有什么意图,所以我删除了它):

import threading

def some_signal():
    print(threading.currentThread().getName(), 'Get signal')

def post_proccesing():
    print(threading.currentThread().getName(), 'Process the signa;')

for i in range(5):
    if i: # means i > 0 because 0 -> False
        t = threading.Thread(target=some_signal) # use default name
        # removed 'else' statement because you need to have a 'w' variable for your call to 'w.start()'
        w = threading.Thread(target=post_proccesing) # use default name
        t.start()
        w.start()
    else: # case where i == 0 -> first iteration
        some_signal()
        post_proccesing()

输出:

MainThread Get signal
MainThread Process the signa;
Thread-1 Get signal
Thread-2 Process the signa;
Thread-3 Get signal
Thread-4 Process the signa;
Thread-5 Get signal
Thread-6 Process the signa;
Thread-7 Get signal
Thread-8 Process the signa;