Skip to main content
 首页 » 编程设计

python之如何避免等待线程完成执行之Python

2025年05月04日12mq0036

我在 Python 中定义了以下结构 -

有两个线程。每个线程垂直向下扫描分支并打印其值。到达该分支的末端时,它沿水平轴向前移动一步。比如,线程 1 将打印 a1、a2 和 a3。同时线程2会扫描b1。当两个线程都执行完后,线程1会跳转到block B,thread 2会跳转到block C执行同样的流程。

当所有 block 都完成后,该过程从头开始。我已经为此编写了一个脚本 -

def printTags(DevObj): 
    if DevObj == None: 
        return -1 
    TagObj = DevObj.tagPointer 
    while TagObj != None: 
        time.sleep(5) 
        print TagObj.id 
        TagObj = TagObj.nextTag 
 
import threading, thread 
 
# temp1 points to Block A. 
# temp2 points to Block B. 
 
while True: 
    t1 = threading.Thread(target=printTags, args=(temp1,)) 
    t2 = threading.Thread(target=printTags, args=(temp2,)) 
    t1.start() 
    t2.start() 
    t1.join() 
    t2.join() 
 
    if temp1.nextDevice != None: 
        temp1 = temp1.nextDevice 
    else: 
        temp1 = start.nextDevice 
 
    if temp2.nextDevice != None: 
        temp2 = temp2.nextDevice 
    else: 
        temp2 = start.nextDevice  

但是,您可以看到,当线程在 block A 和 B 上工作时,线程 1 将比线程 2 花费更多的时间,因为它必须打印更多的值。因此,线程 2 有一段时间未被使用。我想避免这段空闲时间。我该怎么做?

请您参考如下方法:

您可以采用不同的方法,但我想指出其中两种:

首先,使用 Semaphore,这与您的代码一样接近,但实际上并不可取:

from threading import Semaphore 
 
def printTags(DevObj, s): 
    ... 
    s.release() 
    ... 
 
import threading, thread 
 
# temp1 points to Block A. 
# temp2 points to Block B. 
 
 
s = Semaphore(0) 
threads = [ 
    threading.Thread(target=printTags, args=(THING_TO_DO,s)) 
    for THING_TO_DO in THINGS_TO_DO 
] 
for t in threads: 
    t.start() 
 
while True: 
    s.aquire() 
    for t in threads: 
        # give more work 

更好的选择是使用生产者/消费者模式:

from threading import Semaphore 
 
STOP = object() 
 
def printTags(queue): 
    while True: 
        thing_to_process = queue.get() 
        if thing_to_process is STOP: 
            return 
        else: 
            #process  
 
import threading, thread 
 
# temp1 points to Block A. 
# temp2 points to Block B. 
 
THREAD_COUNT = 2 
s = Semaphore(0) 
threads = [ 
    threading.Thread(target=printTags, args=(queue,)) 
    for _ in xrange(THREAD_COUNT) 
] 
 
for thing in things: 
    queue.put(thing) 
for _ in xrange(THREAD_COUNT): 
    queue.put(STOP) 
 
for t in threads: 
    t.start()