在类线程之间发送消息 Python

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14508906/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:40:15  来源:igfitidea点击:

Sending messages between class threads Python

pythonmultithreadingmessaging

提问by Sam Heather

Does anybody know how I can send a variable (or get a variable) from threadOne to threadTwo in this code without using a global variable? If not, how would I operate a global variable? Just define it before both classes and use the global definition in the run function?

有谁知道如何在不使用全局变量的情况下在此代码中将变量(或获取变量)从 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()

Thanks

谢谢

采纳答案by gak

You can use queuesto send messages between threads in a thread safe way.

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

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

回答by ATOzTOA

Here you go, using Lock.

给你,使用Lock.

import threading

print "Press Escape to Quit"

# Global variable
data = None

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

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

        with lock:
            print "Thread one has lock"
            data = "Some value"


class threadTwo(threading.Thread):
    def run(self):
        global data
        print 'ran'
        print "Waiting"

        with lock:
            print "Thread two has lock"
            print data

lock = threading.Lock()

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

Using global variable data.

使用全局变量data

The first thread acquires the lock and write to the variable.

第一个线程获取锁并写入变量。

Second thread waits for data and prints it.

第二个线程等待数据并打印它。

Update

更新

If you have more than two threads which need messages to be passed around, it is better to use threading.Condition.

如果您有两个以上的线程需要传递消息,最好使用threading.Condition.