Georgian
Georgian

Reputation: 73

Python 3 threading , queue

I'm facing with a "little" problem regarding adding data to queue.Queue from a thread.

Environment data: Ubuntu 18.04 / Python 3.6.7 / Python 3.8.5

In the rows below I will post my simplified code. Any help will be appreciated.

from threading import Thread,Lock
from queue  import Queue
from random import randint

thread = None
thread_lock = Lock()
q = Queue()


def worker(number):
    random_number= [str(randint(1,999)),number]
    q.put(random_number)


def first_function(iteration):
    global thread
    some_list=[]
    with thread_lock:
        threads=[]
        if thread is None:
            for iterator in range(iteration):
                thread = Thread(target=worker,args=(iterator,))
                threads.append(thread)
                thread.start()
        for thread_ in threads:
            thread_.join()
        thread = None
    while not q.empty():
        some_list.append(q.get())
    return (some_list)    

print(first_function(10))
print(first_function(5))

My second call will return an empty list. Please give me an idea .

Upvotes: 0

Views: 351

Answers (1)

Adrian97gl
Adrian97gl

Reputation: 26

The problem is with "thread = None" after the method is executed first time on thread is append an <Thread ... > and in second call when you verify "if thread is None", suprize is not None.

Upvotes: 1

Related Questions