【问题标题】:Python threads in embedded Python: How?嵌入式 Python 中的 Python 线程:如何?
【发布时间】:2011-03-10 17:03:33
【问题描述】:

在尝试使用 Python (python.org) C API 时,我发现自己想知道如何在 Python 本身嵌入 C 程序时通过 Python 的 threading 包正确生成线程。一旦 C 函数完成对 Python 代码块的评估,函数PyEval_EvalCode 和 kin 似乎就会终止它“拥有”的线程。粗略地说,从 C 运行以下 Python ...

import threading, time

class MyThread(threading.Thread):
    def __init__(self, num):
        self.num = num
        threading.Thread.__init__(self)
    def run(self):
        print "magic num = %d" % self.num

for x in xrange(1000):
    MyThread(x).start()

... 将在 for 循环完成并且控制从 PyEval_EvalCode (或类似的)C 函数返回后立即完全停止。我们可以观察到这会产生截断的输出。

我在使用以下策略后假设了这种行为:我们可以通过在产生大量线程后休眠来决定何时返回控制,从而在一定程度上决定输出:

for x in xrange(100):
    MyThread(x).start()

# Don't leave just yet; let threads run for a bit
time.sleep(5) # Adjust to taste

我怀疑一种可能的方法是创建一个专门用于嵌入和运行 Python 的新系统线程。在产生 Python 线程之后,Python 代码会在信号量或其他东西上休眠,直到它被告知关闭。那么问题是如何向线程发出整洁关闭的信号?类似地,“main”块可以简单地在所有线程上加入();然后需要从 C 向线程发出信号。

非常感谢您的解决方案..

【问题讨论】:

    标签: python c multithreading embed


    【解决方案1】:

    您是否包含了 pthread 库?如果检测到真正的线程不可用,Python 将回退到虚拟线程

    【讨论】:

      猜你喜欢
      • 2011-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多