简体   繁体   English

暂停线程并将其从另一个脚本唤醒

[英]Pause thread and wake it up from another script

I want a thread to wait for a message from another script. 我希望线程等待来自另一个脚本的消息。

I don't want to use time.sleep() as it creates time gaps and if I need my thread to wake up and continue running, it might delay too much and I'm aiming for fastest performance. 我不想使用time.sleep()因为它会造成时间间隔,如果我需要唤醒我的线程并继续运行,它可能会延迟太多,因此我旨在获得最快的性能。 I don't won't to use while(NOT_BEING_CALLED_BY_THE_OTHER_THREAD) because it will eat up my CPU and I'm also aiming to keep my CPU usage as low as possible (as there will be more thread doing the same at the same time). 我不会使用while(NOT_BEING_CALLED_BY_THE_OTHER_THREAD)因为它会耗尽我的CPU,并且我也希望将CPU使用率保持在尽可能低的水平(因为会有更多线程同时执行此操作) 。

In Pseudo-code it should look like this: 在伪代码中,它应如下所示:

do_stuff()
wait_for_being_called() #Rise immediately after being called (or as soon as possible)
do_more_stuff()

The purpose of this is to use data that wasn't available before being called, there is a script that checks for the data availability (a single thread running) and many which await for the data they need to be available (the single script checks it, and should call them if the data is available). 这样做的目的是使用被调用之前不可用的数据,有一个脚本检查数据的可用性(正在运行一个线程),还有许多脚本正在等待需要的数据(单个脚本检查)它,如果数据可用,则应调用它们)。 It's kind of like std::condition_variable in c++, only I want my other, external script to be able to wake the awaiting script. 有点像c ++中的std::condition_variable ,只是我希望我的其他外部脚本能够唤醒正在等待的脚本。

How can I achieve something like this? 我怎样才能实现这样的目标? What should check_for_events.py contain? check_for_events.py应该包含什么?

#check_for_events.py
for data_node in data_list:
        """
        What do I do here, assuming I have the thread id?
        """

If you have two different scripts, probably the best thing to use is select . 如果您有两个不同的脚本,最好使用select Here's an example of what I mean: 这是我的意思的示例:

from __future__ import print_function
import select
import socket
import sys
import time
from random import randint


def serve():
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    port = randint(10000, 50000)
    with open('.test_port', 'w') as f:
        f.write('{}'.format(port))
    sock.bind(('127.0.0.1', port))
    sock.listen(1)

    not_finished = True
    while not_finished:
        try:
            print('*'*40)
            print('Waiting for connection...')
            conn, addr = sock.accept()
            print('Waiting forever for data')
            select.select([conn], [], [])

            data = conn.recv(2048)
            print('got some data, so now I can go to work!')

            print('-'*40)
            print('Doing some work, doo da doo...')
            print('Counting to 20!')
            for x in range(20):
                print(x, end='\r')
                time.sleep(0.5)
            print('** Done with work! **')
            print('-'*40)

            conn.close()
        except KeyboardInterrupt:
            print('^C caught, quitting!')
            not_finished = False


def call():
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print('Connecting')
    with open('.test_port') as f:
        port = int(f.read())
    sock.connect(('127.0.0.1', port))
    sock.sendall(b'This is a message')
    sock.close()
    print('Done')


if __name__ == '__main__':
    if 'serve' in sys.argv:
        serve()
    elif 'call' in sys.argv:
        call()

This allows the caller to actually communicate information with the runner. 这允许呼叫者实际与跑步者交流信息。 You could also set it up to listen for multiple incoming connections and toss them in the pool to select from, if that's something that you need. 您也可以将其设置为侦听多个传入连接,并将它们扔到池中以进行select (如果需要)。

But if you really just want to block until another program calls you, then you could make this even more simple by removing the parts between conn, add = sock.accept() and conn.close() (other than your own work, of course). 但是,如果您真的只是想阻塞直到另一个程序调用您,那么您可以通过删除conn, add = sock.accept()之间的部分conn, add = sock.accept()conn.close() (除了您自己的工作,课程)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM