X
X
xozzslip2016-10-14 00:39:59
Python
xozzslip, 2016-10-14 00:39:59

Where to store a variable that should be available to all threads?

I have a variable queue = Queue()
Is it possible to store it so that all threads have access to it as the same object, but not pass this queue as an argument.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Kitaev, 2016-10-15
@xozzslip

from threading import Thread
from queue import Queue, Empty
from time import sleep

q = Queue()

def f():
    while True:
        try:
            item = q.get_nowait()
        except Empty:
            return
        else:
            print(item**2)
            sleep(5)


if __name__ == '__main__':
    threads = [Thread(target=f) for _ in range(10)]
    for i in range(100):
        q.put(i)
    for t in threads:
        t.start()

Here is an example of how not to pass a queue to a function. It's just that the function should have a queue in the scope. But it's better to pass, because the explicit is better than the implicit.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question