Multithreaded client in python

时间:2017-12-15 11:28:37

标签: python multithreading python-3.x networking python-3.6

I'm having a problem when I connect to the server, it connects properly and the code in the thread runs perfectly, the problem is that it appears as if I'm not receiving any message, or at least self.data is not updating, I tried checking with print("") and it appears as if the while loop after I start the thread is not reached by the code. Here is my code:

class Client:
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    def __init__(self, address):
        self.sock.connect((address, 10000))
        self.playerID = PID
        self.data = [0, 0, 0, 0, 0]


        iThread = threading.Thread(target=self.game(self.data))
        iThread.daemon = True
        iThread.start()

        while True:
            data = self.sock.recv(2048)
            datas = pickle.loads(data)
            for i in range(0, len(self.data)):
                self.data[i]= datas[i]
            if not data:
                break

    def game(self, data):
        morecode...

1 个答案:

答案 0 :(得分:1)

这是一个实验,其中Thread被赋予没有参数的目标,但目标已经关闭了它所需的参数:

from threading import Thread

import time

def func1(data):
    time.sleep(2)
    data.append(2)


def func(data):

    def func2():
        func1(data)

    print(data)
    t=Thread(target=func2)
    t.start()
    t.join()
    print(data)
    t=Thread(target=lambda: func1(data))
    t.start()
    t.join()
    print(data)


func([0])

输出:

[0]
[0, 2]
[0, 2, 2]

这个答案是为了表明有一些方法可以给Thread一个目标,这是一种封闭形式。