Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/336.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python-linux-立即启动线程_Python_Linux_Multithreading_Delay - Fatal编程技术网

python-linux-立即启动线程

python-linux-立即启动线程,python,linux,multithreading,delay,Python,Linux,Multithreading,Delay,下面是一些示例代码 while True: #main-loop if command_received: thread = Thread(target = doItNOW) thread.start() ...... def doItNOW(): some_blocking_operations() 我的问题是我需要立即启动“一些阻塞操作”(只要收到的命令正确)。 但是因为它们被阻塞了,我不能在我的主循环中执行它们 我也不能将“某些阻塞

下面是一些示例代码

while True: #main-loop
    if command_received:
        thread = Thread(target = doItNOW)
        thread.start()

...... 


def doItNOW():
    some_blocking_operations()
我的问题是我需要立即启动“一些阻塞操作”(只要收到的命令正确)。 但是因为它们被阻塞了,我不能在我的主循环中执行它们 我也不能将“某些阻塞操作”更改为非阻塞

对于“立即”,我的意思是尽快,延迟不超过10毫秒。 (我曾经被耽搁了整整一秒钟)。 如果这是不可能的,持续的延迟也是可以接受的。(但它必须是常量,误差只有几毫秒)

我目前正在开发一个linux系统(Ubuntu,但将来可能会是另一个。永远是linux)

python解决方案将是令人惊奇的。。但换一个总比什么都没有好

有什么想法吗? 提前谢谢

from threading import Thread
class worker(Thread):
    def __init__(self, someParameter=True):
        Thread.__init__(self)
        # This is how you "send" parameters/variables
        # into the thread on start-up that the thread can use.
        # This is just an example in case you need it.
        self.someVariable = someParameter
        self.start() # Note: This makes the thread self-starting,
                     #       you could also call .start() in your main loop.
    def run():
        # And this is how you use the variable/parameter
        # that you passed on when you created the thread.
        if self.someVariable is True:
            some_blocking_operations()

while True: #main-loop
    if command_received:
        worker()
这是以线程方式非阻塞执行
某些阻塞操作()。我不确定你要找的是等待线程完成还是不完成,或者你是否在乎

如果您只想等待“命令”被接收,然后在不等待的情况下执行阻塞操作,验证它是否完成,那么这应该对您有用

Python线程机制 Python将只在一个CPU内核中运行,您在这里所做的只是在CPU中的重叠时钟Inverval上运行多个执行。这意味着CPU中每隔一个周期就会在主线程中执行一次,而阻塞调用的另一个周期将有机会运行一次执行。它们实际上不会并行运行

有一些“你可以,但是……”的线索。。像这个:


您看到的延迟很可能是因为您只能有一个线程运行python代码(GIL和all)。如果阻塞操作是IO,您可以使用gevent。谢谢,但我已经得出了这个结论。我的问题是Thread.start()函数和Thread.run()@federico的有效执行之间存在延迟。我几乎不认为
start()->run()
是您的问题。我测量出两者之间有一微秒的延迟。您是否在注意到执行
某些\u阻塞\u操作()
中的任何操作之前就提到了延迟?您请求的帮助没有详细信息。如果是这种情况,请添加您实际尝试执行的相关代码。