如何在不使用join的情况下向python中的主线程发送信号?

时间:2014-08-06 08:08:58

标签: multithreading python-2.7 signals python-multithreading

我正在尝试从子线程向多线程程序中的主线程发送信号(不能使用多进程)。不幸的是,即使在用尽所有在线阅读材料(我能找到)之后,我也无法清楚地了解如何这样做。我是一个信号和蟒蛇的初学者,所以请耐心等待,并向新手解释。 我不能在进程中使用join方法,因为我希望两个线程同时运行。 以下是我在此处找到的与此主题相关的代码 - http://pymotw.com/2/signal/#signals-and-threads 它并不适合我。

import signal
import threading
import os
import time

def signal_handler(num, stack):
    print 'Received signal %d in %s' % (num, threading.currentThread())

signal.signal(signal.SIGUSR1, signal_handler)

def wait_for_signal():
    print 'Waiting for signal in', threading.currentThread()
    signal.pause()
    print 'Done waiting'

# Start a thread that will not receive the signal
receiver = threading.Thread(target=wait_for_signal, name='receiver')
receiver.start()
time.sleep(0.1)

def send_signal():
    print 'Sending signal in', threading.currentThread()
    os.kill(os.getpid(), signal.SIGUSR1)

sender = threading.Thread(target=send_signal, name='sender')
sender.start()
sender.join()

# Wait for the thread to see the signal (not going to happen!)
print 'Waiting for', receiver
signal.alarm(2)
receiver.join()

如果可能,请使用多线程示例进行说明。 提前谢谢!

1 个答案:

答案 0 :(得分:2)

信号和线程真的,真的不能很好地一起玩。

考虑使用Event或其他同步机制。以下示例创建一个“event”对象,然后将其传递给两个线程。一个人等待两秒钟,然后发出信号通知对方打印出一条消息然后退出。

import threading, time

def flagger_thread(event):
    """
    wait for two seconds, then make 'event' fire
    """
    time.sleep(2)
    event.set()

def waiter_thread(event):
    print("Waiting for event")
    if event.wait(5):
        print("event set.")
    else:
        print("Timed out.")

stop_event = threading.Event()
threading.Thread(target=flagger_thread, args=[stop_event]).start()
threading.Thread(target=waiter_thread, args=[stop_event]).start()

# wait for all threads to exit
for t in threading.enumerate():
    if t != threading.current_thread():
        t.join()

输出

Waiting for event
event set.