Skip to content

Instantly share code, notes, and snippets.

@initialed85
Last active May 19, 2017 03:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save initialed85/821ed2109d531d897bdc56504df86075 to your computer and use it in GitHub Desktop.
Save initialed85/821ed2109d531d897bdc56504df86075 to your computer and use it in GitHub Desktop.
Demonstration of Python threading.RLock
from threading import RLock, Thread
import copy
import datetime
import random
import time
class SharedObject(object):
def __init__(self):
self._shared_variable = None
self._lock = RLock()
@property
def shared_variable(self):
with self._lock:
return copy.copy(self._shared_variable)
@shared_variable.setter
def shared_variable(self, shared_variable):
with self._lock:
self._shared_variable = copy.copy(shared_variable)
def write_worker(index, shared_object):
global _STOP_THREADS
while not _STOP_THREADS:
shared_variable = random.randint(0, 255)
before = datetime.datetime.now()
shared_object.shared_variable = shared_variable
after = datetime.datetime.now()
print 'thread {0} wrote {1} in {2}'.format(
index, shared_variable, after - before
)
time.sleep(1)
def read_worker(index, shared_object):
global _STOP_THREADS
while not _STOP_THREADS:
before = datetime.datetime.now()
shared_variable = shared_object.shared_variable
after = datetime.datetime.now()
print 'thread {0} read {1} in {2}'.format(
index, shared_variable, after - before
)
time.sleep(1)
_STOP_THREADS = False
so = SharedObject()
ts = []
for i in range(0, 512):
ts += [Thread(
target=write_worker if i % 2 == 0 else read_worker,
args=(i, so,)
)]
ts[-1].start()
while 1:
try:
time.sleep(1)
except KeyboardInterrupt:
_STOP_THREADS = True
break
for t in ts:
t.join()
@initialed85
Copy link
Author

This script defines a SharedObject with RLock protection around a property called "shared_variable".

It then spins up 512 threads; half of them write to the object, half of them read from it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment