在后台运行功能并继续程序

时间:2014-12-14 22:05:13

标签: python multithreading

我正在尝试在后台运行一个函数,同时继续使用python中的代码。

我想在后台运行的功能来自socket。寻找特定数据来关闭程序。

这是功能:

def receive():
    host = ""
    port = 13000
    buf = 1024
    addr = (host,port)
    Sock = socket(AF_INET, SOCK_DGRAM)
    Sock.bind(addr)
    (data, addr) = Sock.recvfrom(buf)
    return data

以下是我要运行的代码:

while True:
    r = receive()
    if r == "stop":
        break
    #Cannot get past here, because of the function running.
    #Should loop over and over, until stop data is received
    print "Running program"

我尝试过线程,r = threading.Thread(target=receive())并没有快乐。

2 个答案:

答案 0 :(得分:1)

您无法从调用的线程的目标函数返回到调用线程。相反,您需要一些线程间通信系统。下面是使用Python的Queue在两个线程之间传递接收的数据报的示例。我已经使用threading.Event来指示接收器线程何时停止。

#!/usr/bin/env python

import socket
import threading
from queue import Empty, Queue


class DatagramReceiver(threading.Thread):
    def __init__(self, stop, queue):
        super().__init__()
        self._stop = stop
        self._queue = queue

    def run(self):
        with socket.socket(AF_INET, SOCK_DGRAM) as sock:
            sock.bind(('', 13000))
            while not self._stop.is_set():
                data = sock.recvfrom(1024)[0]
                if data == 'stop':
                    self._stop.set()
                    break
                self._queue.put(data)


def main():
    stop = threading.Event()
    queue = Queue()

    reader = DatagramReceiver(stop, queue)
    reader.deamon = True
    reader.start()

    while not stop.is_set():
        user_input = input('Press RETURN to print datagrams, or q quit')
        if user_input == 'q':
            break
        while True:
            try:
                datagram = queue.get_nowait()
            except Empty:
                break
            print(datagram)

    stop.set()
    reader.join()

答案 1 :(得分:0)

新秀错误:

r = threading.Thread(target=receive())

我没有从receive()

中删除括号
r = threading.Thread(target=receive)