在Python中使用队列在两个线程之间共享数据

时间:2017-11-23 23:18:57

标签: python python-multithreading

我有两个主题。

def collectorFunction():
    # collectInformation
    # add to List
    list.append(myReceivedData)

def senderFunction):
    time.sleep(60)
    sendList.append(list[:])
    del list[:]
    # send information

t1 = Thread(target = collectorFunction)
t1.daemon = True
t1.start()
t2 = Thread(target = senderFunction)
t2.daemon = True
t2.start()

我想做的是在后台运行一个线程,不断通过UDP广播收集信息。我获取该信息,将其排队,并将其发送到另一个位置。基本上是监控设备。我认为通过JSON调用发送大量数据的网络密集程度较低。

目前我正在使用全局变量。但我不愿意使用它。我刚读过队列。我见过的大多数示例都会显示此示例中的collectorFunction,放入队列,并且senderFunction从队列中获取。

但我需要的是让collectorFunction无限期地放入队列,使用senderFunction从队列中获取所有内容,处理,然后等待60秒再重试。

我见过的一个例子显示:

def func2(num, q):
    while num < 100000000:
        num = q.get()
        print num,

不太确定如何根据我的需要重写这个?

也许

def senderFunction(queue):
    while 1:
        while len(queue) > 0:
            item = queue.get()
            # do what I need with the items
        time.sleep(60)

这有意义吗?有没有更好的方法呢?

0 个答案:

没有答案
相关问题