首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >python - linux -立即启动线程

问python - linux -立即启动线程
EN

Stack Overflow用户
提问于 2015-05-15 17:55:46
回答 1查看 110关注 0票数 1

下面是一些示例代码

代码语言:javascript
复制
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解决方案将会很棒..但换一个总比什么都没有好

有什么想法吗?提前感谢

EN

回答 1

Stack Overflow用户

发布于 2015-05-15 18:02:32

代码语言:javascript
复制
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中每隔一个周期就会在主线程中执行一次,而另一个阻塞调用将有机会运行一次执行。它们实际上不会并行运行。

有一些“你可以,但是...”线程..就像这样:

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30256508

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档