线程没有同时运行。 (蟒蛇)

时间:2014-04-06 23:58:50

标签: python multithreading p2p python-multithreading instant-messaging

在使用线程模块的Python中,我的程序不会运行我同时创建的2个线程。我正在尝试使用P2P创建即时消息程序,我不知道问题是与套接字模块有关,还是我做错了什么。代码:

import socket
import threading

class Receiver:
    def __init__(self):

        # Create socket that supports IPv4, TCP Protocol
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        print "Socket created."
        # Requests for IP of host (DNS)
        dns = "localhost"
        HOST = ''
        PORT = 57492
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.bind((HOST, PORT)) # Listens on all interfaces...
        print 'Listening on port 25565'
        s.listen(True) # Listen on the newly created socket... 
        conn, addr = s.accept()
        print 'Connected in port 25565'
        global data
        while 1:
            data = conn.recv(1024)
            print data
        s.close()

    def Sender(self):

        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        dns = "localhost"
        HOST = socket.gethostbyname(dns)
        PORT = 57492    
        # Connect to server
        s.connect((HOST, PORT))

        print "Socket connected to " + dns + " on IP " + HOST

        while 1:

            # Assign message to be sent to server to a variable
            message = raw_input("Message to be sent to server: ")

            #Send the actual message to server
            s.sendall(message)
        print "Message sent successfully"
        s.close()
    def go(self):

        th1 = threading.Thread()
        th2 = threading.Thread(target=self.Sender)
        th1.start()
        th2.start()

t = Receiver()
t.go()

3 个答案:

答案 0 :(得分:1)

这里有两个问题。首先,th1永远不会被赋予执行方法,所以当你在它上面调用start时,线程什么也不做,并立即退出。第二个问题是你在Receiver类的构造函数中进行永久性工作(无限循环)。这意味着行t = Receiver()将(基本上)永远不会返回,并且您永远不会打电话给go()

这是一个示例,删除了所有套接字的内容,如何在您已设置的基本框架中启动两个线程:

#!/usr/bin/python

import threading
import time
import signal

class Communicator:
    def __init__(self):
        self.__stop = False

    def __runSender(self):
        # setup sender here
        while not self.__stop:
            # run sender loop here
            print "in sender"
            time.sleep(1)
        print "stopped sender"

    def __runReceiver(self):
        # setup receiver here
        while not self.__stop:
            # run recevier loop here
            print "in receiver"
            time.sleep(1)
        print "stopped receiver"

    def start(self):
        senderThread = threading.Thread(target=self.__runSender)
        receiverThread = threading.Thread(target=self.__runReceiver)
        senderThread.start()
        receiverThread.start()
    def stop(self):
        self.__stop = True


c = Communicator()

def handleKill(n, frame):
    print "HANDLING SIGNAL"
    c.stop()

signal.signal(signal.SIGINT, handleKill)
print "Starting communication, hit CTRL-c to stop"
c.start()
signal.pause()

答案 1 :(得分:0)

Sendergo方法没有缩进,因此不属于Receiver,这意味着当您定义th2时,没有self.Sender

答案 2 :(得分:0)

这些行:

th1 = threading.Thread()
th2 = threading.Thread(target=self.Sender)

th1无法运行任何操作。

另一个值得关注的问题是你有一个全局变量data,如果你真的打算多次运行这个整个类,你的多个线程可能会破坏那个变量并给你垃圾结果。或者,您打算同时运行SenderReceiver吗?你所拥有的答案可能是传递th1 target=self的{​​{1}}参数,但这似乎是一种运行线程应用程序(线程内的线程?)的可怕方法。

如果是后者,最好将Sender和Receiver分离为单独的方法,并设置线程以定位这些单独的方法:

class Conversation:
    def __init__(self):
        pass

    def receiver(self):
        ...code code code...

    def sender(self):
        ...code code code...

    def go(self):

        th1 = threading.Thread(target=self.receiver)
        th2 = threading.Thread(target=self.render)
        th1.start()
        th2.start()

我不知道这是否能彻底解决您的问题,但这只是一个开始:它使得th1有事可做。

我也认为你还需要一些线程安全的方法来告诉你的循环结束。

最后,请记住,您无法安全地在这些线程之间来回传递数据(如果这是您的意图),并使用当前的代码。