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