下面是一些示例代码
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解决方案将会很棒..但换一个总比什么都没有好
有什么想法吗?提前感谢
发布于 2015-05-15 18:02:32
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中每隔一个周期就会在主线程中执行一次,而另一个阻塞调用将有机会运行一次执行。它们实际上不会并行运行。
有一些“你可以,但是...”线程..就像这样:
https://stackoverflow.com/questions/30256508
复制相似问题