Skip to content

Update singleton_thread_locals.py #252

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jun 17, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions examples/providers/singleton_thread_locals.py
Original file line number Diff line number Diff line change
@@ -1,26 +1,26 @@
"""`ThreadLocalSingleton` providers example."""

import threading
import Queue
import queue

import dependency_injector.providers as providers


def example(example_object, queue):
def example(example_object, queue_object):
"""Put provided object in the provided queue."""
queue.put(example_object)
queue_object.put(example_object)


# Create thread-local singleton provider for some object (main thread):
thread_local_object = providers.ThreadLocalSingleton(object)

# Create singleton provider for thread-safe queue:
queue = providers.Singleton(Queue.Queue)
queue_factory = providers.ThreadSafeSingleton(queue.Queue)

# Create callable provider for example(), inject dependencies:
example = providers.DelegatedCallable(example,
example_object=thread_local_object,
queue=queue)
queue_object=queue_factory)

# Create factory provider for threads that are targeted to execute example():
thread_factory = providers.Factory(threading.Thread,
Expand All @@ -43,8 +43,8 @@ def example(example_object, queue):
# Making some asserts (main thread):
all_objects = set()

while not queue().empty():
all_objects.add(queue().get())
while not queue_factory().empty():
all_objects.add(queue_factory().get())

assert len(all_objects) == len(threads)
# Queue contains same number of objects as number of threads where
Expand Down