2016-08-17 00:03:26 +03:00
|
|
|
"""`ThreadLocalSingleton` providers example."""
|
|
|
|
|
|
|
|
import threading
|
2020-06-17 04:53:00 +03:00
|
|
|
import queue
|
2016-08-17 00:03:26 +03:00
|
|
|
|
|
|
|
import dependency_injector.providers as providers
|
|
|
|
|
|
|
|
|
2020-06-17 04:53:00 +03:00
|
|
|
def example(example_object, queue_object):
|
2017-04-18 23:38:04 +03:00
|
|
|
"""Put provided object in the provided queue."""
|
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
|
|
|
|
2016-08-17 00:03:26 +03:00
|
|
|
# Create thread-local singleton provider for some object (main thread):
|
|
|
|
thread_local_object = providers.ThreadLocalSingleton(object)
|
|
|
|
|
|
|
|
# Create singleton provider for thread-safe queue:
|
2020-06-17 04:53:00 +03:00
|
|
|
queue_factory = providers.ThreadSafeSingleton(queue.Queue)
|
2016-08-17 00:03:26 +03:00
|
|
|
|
|
|
|
# Create callable provider for example(), inject dependencies:
|
2020-07-18 07:40:14 +03:00
|
|
|
example = providers.DelegatedCallable(
|
|
|
|
example,
|
|
|
|
example_object=thread_local_object,
|
|
|
|
queue_object=queue_factory,
|
|
|
|
)
|
2016-08-17 00:03:26 +03:00
|
|
|
|
2020-07-18 07:40:14 +03:00
|
|
|
# Create factory for threads that are targeted to execute example():
|
|
|
|
thread_factory = providers.Factory(threading.Thread, target=example)
|
2016-08-17 00:03:26 +03:00
|
|
|
|
2016-08-18 00:59:44 +03:00
|
|
|
if __name__ == '__main__':
|
|
|
|
# Create 10 threads for concurrent execution of example():
|
|
|
|
threads = []
|
2016-11-02 19:22:17 +03:00
|
|
|
for thread_number in range(10):
|
2020-07-18 07:40:14 +03:00
|
|
|
threads.append(
|
|
|
|
thread_factory(name='Thread{0}'.format(thread_number)),
|
|
|
|
)
|
2016-08-17 00:03:26 +03:00
|
|
|
|
2016-08-18 00:59:44 +03:00
|
|
|
# Start execution of all created threads:
|
|
|
|
for thread in threads:
|
|
|
|
thread.start()
|
2016-08-17 00:03:26 +03:00
|
|
|
|
2016-08-18 00:59:44 +03:00
|
|
|
# Wait while threads would complete their work:
|
|
|
|
for thread in threads:
|
|
|
|
thread.join()
|
2016-08-17 00:03:26 +03:00
|
|
|
|
2016-08-18 00:59:44 +03:00
|
|
|
# Making some asserts (main thread):
|
|
|
|
all_objects = set()
|
2016-08-17 00:03:26 +03:00
|
|
|
|
2020-06-17 04:53:00 +03:00
|
|
|
while not queue_factory().empty():
|
|
|
|
all_objects.add(queue_factory().get())
|
2016-08-17 00:03:26 +03:00
|
|
|
|
2016-08-18 00:59:44 +03:00
|
|
|
assert len(all_objects) == len(threads)
|
|
|
|
# Queue contains same number of objects as number of threads where
|
|
|
|
# thread-local singleton provider was used.
|