2

I have a class A extended from threading.Thread, now I want to pass the parameters into the running thread , I can get the thread I wanted by the following script:

find_thread = None
for thread in enumerate():
    if thread.isAlive():
        name = thread.name.split(',')[-1]
        if name == player_id:
            find_thread = thread #inject the parameter into this thread
            break

Where find_thread is an instance of threading.Thread and I have a queue in find_thread.

class A(threading.Thread):
    def __init__(self,queue):
        threading.Thread.__init__(self)
        self.queue =queue
    def run():
        if not self.queue.empty(): #when it's running,I want to pass the parameters here
            a=queue.get()
            process(a) #do something

Is it possible to do this and how?

1
  • 1
    Well you're already familiar with queue and have a queue.get (recommend get_nowait() instead). So why not just use queue.put_nowait() from whatever thread you want to and have A leverage the queue.get() you have? Commented Sep 11, 2017 at 11:58

1 Answer 1

2

Everything seems fine with your code, you just need to slighty modify it. You've already used threading.Queue I believe , you also used the queue's get method so I wonder why you weren't able to use its put method:

for thread in enumerate():
    if thread.isAlive():
        name = thread.name.split(',')[-1]
        if name == player_id:
            find_thread = thread
            find_thread.queue.put(...)  # put something here
            break

class A(threading.Thread):
    def __init__(self,queue):
        threading.Thread.__init__(self, queue)
        self.queue = queue
    def run():
        a = queue.get()                 # blocks when empty
        process(a)

queue = Queue()
thread1 = A(queue=queue,...)

I removed the check for the empty queue, queue.get blocks when the queue is empty making the check gratuitous here, this is because a is needed by your thread for processing.

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

1 Comment

i think there is a typo, in line " threading.Thread.__init__(self, queue)", you don't need to pass the queue to the init, this will raise an error

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.