Python简单线程间通信

本节主要举一个简单的线程间通信的例子,利用线程安全的数据结构queue.Queue保存线程间通信的内容,

import queue
from threading import Thread
from random import randint


class WriteThread(Thread):
    def __init__(self,sid,queue):
        Thread.__init__(self)
        self.sid = sid
        self.queue = queue
    def run(self):
        data = [randint(1,10) for _ in range(0,5)]
        self.queue.put((self.sid,data)) #--> 这里要主要,把线程号和data放在一起 作为一个元组输入到queue中,否则就会提示整数不是一个迭代对象

class ReadThread(Thread):
    def __init__(self,queue):
        Thread.__init__(self)
        self.queue = queue
    def run(self):
        while True:
            sid, data  = self.queue.get()
            print("Data read from thread {0},data is {1}".format(sid,data))

q= queue.Queue()
WThread = [WriteThread(i, q) for i in range(0,5)]
RThread = ReadThread(q)

for t in WThread:
    t.start()
RThread.start()

 

转载于:https://www.cnblogs.com/BGPYC/p/7583233.html

你可能感兴趣的:(Python简单线程间通信)