【问题标题】:python - linux - starting a thread immediatelypython - linux - 立即启动一个线程
【发布时间】:2015-05-15 09:55:45
【问题描述】:

这里有一些示例代码

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

...... 


def doItNOW():
    some_blocking_operations()

我的问题是我需要“some_blocking_operations”来立即启动(只要 command_received 为 True)。 但由于它们阻塞了我无法在我的主循环中执行它们 而且我也不能将“some_blocking_operations”更改为非阻塞

对于“立即”,我的意思是尽快,延迟不超过 10 毫秒。 (我曾经有一整秒的延迟)。 如果不可能,那么持续的延迟也是可以接受的。 (但它必须是恒定的。只有几毫秒的错误)

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

一个 python 解决方案会很棒.. 但一个不同的解决方案总比没有好

有什么想法吗? 提前谢谢

【问题讨论】:

  • 您看到的延迟很可能是因为您只能有一个运行 python 代码的线程(GIL 和所有线程)。如果阻塞操作是 IO,你可以使用 gevent。

标签: python linux multithreading delay


【解决方案1】:
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()

这是some_blocking_operations() 以线程方式的非阻塞执行。我不确定您要寻找的是实际等待线程完成,还是您甚至在乎?

如果您只想等待接收“命令”,然后执行阻塞操作而不等待它,验证它是否完成,那么这应该适合您。

Python 线程机制

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

有一些“你可以,但是......”的主题。就像这个:

【讨论】:

  • 谢谢,但我已经得出了这个结论。我的问题是Thread.start()函数和Thread.run()的有效执行之间存在延迟
  • @federico 我几乎不认为start() -> run() 是您的问题。我正在测量两者之间的一微秒延迟。在您注意到some_blocking_operations() 中的任何内容执行之前,您是否可能指的是延迟?如果是这种情况,您正在寻求帮助而没有详细信息,请添加您实际尝试执行的相关代码。
猜你喜欢
  • 2011-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-20
  • 2014-07-15
  • 2016-09-06
  • 1970-01-01
相关资源
最近更新 更多