在类线程Python之间发送消息

Sam*_*her 7 python messaging multithreading

有没有人知道如何在不使用全局变量的情况下在此代码中从threadOne向threadTwo发送变量(或获取变量)?如果没有,我将如何操作全局变量?只需在两个类之前定义它并在run函数中使用全局定义?

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()
Run Code Online (Sandbox Code Playgroud)

谢谢

gak*_*gak 17

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

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
Run Code Online (Sandbox Code Playgroud)


ATO*_*TOA 6

给你,使用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()
Run Code Online (Sandbox Code Playgroud)

使用全局变量data

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

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

更新

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

  • 队列会自动为您处理锁定。自己处理锁定代码会给您的代码(以及维护/调试噩梦)增加不必要的开销。 (3认同)
  • 使用队列而不是带有锁的全局变量来将数据从一个线程发送到另一个线程几乎总是更好。您应该从队列开始,除非有充分的理由*不*使用队列。请参阅以下 Gerald Kaszuba 的回答 (2认同)