这里是一些示例代码
while True: #main-loop
if command_received:
thread = Thread(target = doItNOW)
thread.start()
......
def doItNOW():
some_blocking_operations()
我的问题是我需要“some_blocking_operations”来立即启动(只要 command_received 为真)。 但是因为它们被阻塞了,所以我无法在我的主循环中执行它们 而且我也无法将“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()
这是以线程方式非阻塞地执行some_blocking_operations()
。我不确定您正在寻找的是真正等待线程完成还是不,或者您是否关心?
如果您只想等待接收到“命令”,然后在不等待它的情况下执行阻塞操作,验证它是否完成,那么这应该适合您。
Python 线程机制
Python 将仅在一个 CPU 内核中运行,您在这里所做的只是在 CPU 中的重叠时钟间隔上运行多个执行。这意味着 CPU 中每隔一个周期就会在主线程中执行一次,而另一个你的阻塞调用将有机会运行一次执行。它们实际上不会并行运行。
有一些“你可以,但是......”的话题......就像这个:
关于python - linux - 立即启动一个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30256508/