2020-09-01 20:04:48 +00:00
|
|
|
"""`ThreadLocalSingleton` provider example."""
|
2016-08-16 21:03:26 +00:00
|
|
|
|
|
|
|
import threading
|
2020-06-17 01:53:00 +00:00
|
|
|
import queue
|
2016-08-16 21:03:26 +00:00
|
|
|
|
2020-09-01 20:04:48 +00:00
|
|
|
from dependency_injector import providers
|
2016-08-16 21:03:26 +00:00
|
|
|
|
|
|
|
|
2020-09-01 20:04:48 +00:00
|
|
|
def put_in_queue(example_object, queue_object):
|
2020-06-17 01:53:00 +00:00
|
|
|
queue_object.put(example_object)
|
2016-08-16 21:03:26 +00:00
|
|
|
|
2016-11-15 12:32:23 +00:00
|
|
|
|
2016-08-16 21:03:26 +00:00
|
|
|
thread_local_object = providers.ThreadLocalSingleton(object)
|
2020-09-01 20:04:48 +00:00
|
|
|
queue_provider = providers.ThreadSafeSingleton(queue.Queue)
|
|
|
|
put_in_queue = providers.Callable(
|
|
|
|
put_in_queue,
|
2020-07-18 04:40:14 +00:00
|
|
|
example_object=thread_local_object,
|
2020-09-01 20:04:48 +00:00
|
|
|
queue_object=queue_provider,
|
|
|
|
)
|
|
|
|
thread_factory = providers.Factory(
|
|
|
|
threading.Thread,
|
|
|
|
target=put_in_queue.provider,
|
2020-07-18 04:40:14 +00:00
|
|
|
)
|
2016-08-16 21:03:26 +00:00
|
|
|
|
|
|
|
|
2016-08-17 21:59:44 +00:00
|
|
|
if __name__ == '__main__':
|
|
|
|
threads = []
|
2016-11-02 16:22:17 +00:00
|
|
|
for thread_number in range(10):
|
2020-07-18 04:40:14 +00:00
|
|
|
threads.append(
|
|
|
|
thread_factory(name='Thread{0}'.format(thread_number)),
|
|
|
|
)
|
2016-08-17 21:59:44 +00:00
|
|
|
for thread in threads:
|
|
|
|
thread.start()
|
|
|
|
for thread in threads:
|
|
|
|
thread.join()
|
2016-08-16 21:03:26 +00:00
|
|
|
|
2016-08-17 21:59:44 +00:00
|
|
|
all_objects = set()
|
2020-09-01 20:04:48 +00:00
|
|
|
while not queue_provider().empty():
|
|
|
|
all_objects.add(queue_provider().get())
|
2016-08-16 21:03:26 +00:00
|
|
|
|
2016-08-17 21:59:44 +00:00
|
|
|
assert len(all_objects) == len(threads)
|
|
|
|
# Queue contains same number of objects as number of threads where
|
|
|
|
# thread-local singleton provider was used.
|