2

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...
6
  • Does game return anything? Commented Dec 15, 2017 at 11:42
  • Hi, no, it only sends messages to the server and updates a list Commented Dec 15, 2017 at 11:45
  • 1
    It seems you are calling self.game(self.data) when you create the Thread, rather than letting the thread call it. Commented Dec 15, 2017 at 11:46
  • How should I get the Thread to call my game function? Commented Dec 15, 2017 at 11:48
  • Have you looked around to see any examples of creating a thread with a target that has arguments? Commented Dec 15, 2017 at 11:49

1 Answer 1

1

Here is an experiment where a Thread is given targets without arguments, but the target already closes over the arguments it needs:

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])

Output:

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

This answer is here to show that there are ways to give a Thread a target which is a form of closure.

Sign up to request clarification or add additional context in comments.

1 Comment

I't alredy worked, thank you, I followed you're advice and checked how to use a thread with and argument, it apears the argument is a tupple so i had to specify the argument in that tuple, like this: iThread = threading.Thread(target=self.game, args=(self.data,))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.