Skip to content
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

INT-78: Add a helper class for concurrency #40

Merged
merged 1 commit into from
Nov 4, 2019
Merged
Show file tree
Hide file tree
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: 14 additions & 0 deletions ns1/helpers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
from threading import Lock


class SingletonMixin(object):
"""double-locked thread safe singleton"""
_instance = None
_lock = Lock()

def __new__(cls, *args, **kwargs):
if cls._instance is None:
with cls._lock:
if cls._instance is None:
cls._instance = object.__new__(cls, *args, **kwargs)
return cls._instance
67 changes: 67 additions & 0 deletions tests/unit/test_helpers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import multiprocessing
import pytest
import threading

from uuid import uuid4

import ns1.helpers

try: # Python 3.3 +
import queue
except ImportError:
import Queue as queue


JOIN_TIMEOUT = 2


class A(ns1.helpers.SingletonMixin):
def __init__(self):
self.uuid = uuid4()


class B(ns1.helpers.SingletonMixin):
def __init__(self):
self.uuid = uuid4()


def test_singleton_mixin():
"""
it should be the same instance per mixed-in class
it should not be the same instance across subclassers
"""
a, a2 = A(), A()
b, b2 = B(), B()

assert a is a2
assert b is b2

assert a is not b


@pytest.mark.parametrize('queue_class,process,repetitions', [
(multiprocessing.Queue, multiprocessing.Process, 64),
(queue.Queue, threading.Thread, 64),
])
def test_singleton_mixin_with_concurrency(queue_class, process, repetitions):
"""
it should hold up under multiple processes or threads
"""
def inner(queue):
a = A()
b = A()
queue.put((a.uuid, b.uuid))

test_queue = queue_class()
processes = []
for _ in range(repetitions):
p = process(target=inner, args=(test_queue,))
p.start()
processes.append(p)

seen_uuids = set()
while len(seen_uuids) < repetitions:
a, b = test_queue.get(timeout=JOIN_TIMEOUT)
assert a is b
assert a not in seen_uuids
seen_uuids.add(a)