python - 在类线程之间发送消息 Python

标签 python multithreading messaging

有人知道如何在这段代码中不使用全局变量就可以将变量从 threadOne 发送(或获取变量)到 threadTwo 吗?如果没有,我将如何操作全局变量?只需在两个类之前定义它并在运行函数中使用全局定义?

import threading

print "Press Escape to Quit"

class threadOne(threading.Thread): #I don't understand this or the next line
    def run(self):
        setup()

    def setup():
        print 'hello world - this is threadOne'


class threadTwo(threading.Thread):
    def run(self):
        print 'ran'

threadOne().start()
threadTwo().start()

谢谢

最佳答案

您可以使用 queues以线程安全的方式在线程之间发送消息。

def worker():
    while True:
        item = q.get()
        do_work(item)
        q.task_done()

q = Queue()
for i in range(num_worker_threads):
     t = Thread(target=worker)
     t.daemon = True
     t.start()

for item in source():
    q.put(item)

q.join()       # block until all tasks are done

关于python - 在类线程之间发送消息 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14508906/

相关文章:

c++ - std::map 线程安全

multithreading - Perl 线程 - 共享哈希引用

c++ - 为什么我的 MFC DLL 在接近启动时在单个线程上死锁?

php - 获取线程中的最新消息

python - 将上下文从一个序列化程序传递到另一个序列化程序?

python - 有没有一种简单的方法可以将步骤定义为给定和何时

class - 计算一个类的实例?

python - 如何为数据框的特定子集绘制图表

javascript - 奇怪的 HTML5 Worker JavaScript 代码(消息)

android - 如何在不打开 WhatsApp 的情况下向 WhatsApp 组发送消息?