Python中的线程问题

时间:2016-02-24 09:20:24

标签: python multithreading

我正在编写点对点UDP连接,并决定使用单独的线程进行输入和输出:

import socket
import thread


def wait_response(s):
    while True:
        data, addr = s.recvfrom(1024)
        if data:
            data = data.decode('utf-8')
            print("Received from server: " + data)


def main():
    host = ''
    port = 5000
    server = (my_ipv4, 6000)

    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.bind((host, port))

    d = thread.start_new_thread(wait_response(s))
    d.setDaemon(True)
    d.start()

    message = input("->")

    while message != 'q':
        s.sendto(message.encode('utf-8'), server)
        message = input("->")
    s.close()

if __name__ == '__main__':
        main()  

它在多线程之前以某种方式工作,所以我的问题只是关于并发性:为什么我在控制台中看不到message = input("->")的执行?

1 个答案:

答案 0 :(得分:1)

试试这个,也许你应该需要threading模块,thread模块用于非常低级别的工作,在这样的级别threading更好:

import socket
from threading import Thread


def wait_response(s):
    while True:
        data, addr = s.recvfrom(1024)
        if data:
            data = data.decode('utf-8')
            print("Received from server: " + data)


def main():
    host = ''
    port = 5000
    server = ('', 6000)

    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.bind((host, port))

    d = Thread(target=wait_response, args = (s,))
    d.setDaemon(True)
    d.start()

    message = input("->")

    while message != 'q':
        s.sendto(message.encode('utf-8'), server)
        message = input("->")
    s.close()

if __name__ == '__main__':
        main()