Skip to content

Instantly share code, notes, and snippets.

@novel
Created February 12, 2011 14:42
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 novel/823797 to your computer and use it in GitHub Desktop.
Save novel/823797 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import threading
import time
class Foo(object):
def modify_bar(self, **kwargs):
bar_id = kwargs['bar_id']
print "working on bar id = %s" % bar_id
time.sleep(3)
print "done with bar id = %s" % bar_id
if __name__ == "__main__":
class ModifyBarThread(threading.Thread):
def __init__(self, foo, bar_id):
self.foo = foo
self.bar_id = bar_id
threading.Thread.__init__(self)
def run(self):
self.foo.modify_bar(bar_id=self.bar_id)
foo = Foo()
threads = []
for i in range(3):
thread = ModifyBarThread(foo, 1)
threads.append(thread)
thread.start()
[thread.join() for thread in threads]
import threading
import time
def synchronize(field_name):
def inner_decorator(func):
def wrapper(self, *args, **kwargs):
object_id = kwargs[field_name]
ready_to_start = False
while not ready_to_start:
with self._active_bars_lock:
if object_id not in self._active_bars:
self._active_bars.append(object_id)
ready_to_start = True
if not ready_to_start:
time.sleep(1.0)
try:
ret = func(self, *args, **kwargs)
finally:
with self._active_bars_lock:
self._active_bars.remove(object_id)
return ret
return wrapper
return inner_decorator
class Foo(object):
def __init__(self):
self._active_bars = []
self._active_bars_lock = threading.Lock()
@synchronize('bar_id')
def modify_bar(self, **kwargs):
bar_id = kwargs['bar_id']
print "working on bar id = %s" % bar_id
time.sleep(3)
print "done with bar id = %s" % bar_id
if __name__ == "__main__":
class ModifyBarThread(threading.Thread):
def __init__(self, foo, bar_id):
self.foo = foo
self.bar_id = bar_id
threading.Thread.__init__(self)
def run(self):
self.foo.modify_bar(bar_id=self.bar_id)
foo = Foo()
threads = []
for i in range(3):
thread = ModifyBarThread(foo, 1)
threads.append(thread)
thread.start()
[thread.join() for thread in threads]
if __name__ == "__main__":
class ModifyBarThread(threading.Thread):
def __init__(self, foo, bar_id):
self.foo = foo
self.bar_id = bar_id
threading.Thread.__init__(self)
def run(self):
self.foo.modify_bar(bar_id=self.bar_id)
foo = Foo()
threads = []
for i in range(5):
thread = ModifyBarThread(foo, 0 if i == 2 else 1)
threads.append(thread)
thread.start()
[thread.join() for thread in threads]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment