Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Examining shared mutable objects in threading
import random
import threading
import time
class MyObject(object):
thread_id = None
obj = MyObject()
def target(obj_shared, sleeps):
for sleep in sleeps:
time.sleep(sleep)
thread_id = str(threading.current_thread())
print thread_id, obj_shared.thread_id
obj_shared.thread_id = thread_id
def get_random_sleeptime():
return random.choice(range(0, 30, 2)) / 10.0
sleeps1 = [get_random_sleeptime() for _ in xrange(5)]
thread1 = threading.Thread(target=target, args=(obj, sleeps1))
sleeps2 = [get_random_sleeptime() for _ in xrange(5)]
thread2 = threading.Thread(target=target, args=(obj, sleeps2))
thread1.start()
thread2.start()
max_sleep = int(max(sum(sleeps1), sum(sleeps2)))
for _ in xrange(max_sleep):
time.sleep(1)
print obj.thread_id
thread1.join()
thread2.join()
$ python threading_test.py
<Thread(Thread-1, started 123145413861376)> None
<Thread(Thread-1, started 123145413861376)>
<Thread(Thread-2, started 123145418067968)> <Thread(Thread-1, started 123145413861376)>
<Thread(Thread-1, started 123145413861376)> <Thread(Thread-2, started 123145418067968)>
<Thread(Thread-2, started 123145418067968)> <Thread(Thread-1, started 123145413861376)>
<Thread(Thread-2, started 123145418067968)>
<Thread(Thread-1, started 123145413861376)> <Thread(Thread-2, started 123145418067968)>
<Thread(Thread-1, started 123145413861376)>
<Thread(Thread-1, started 123145413861376)>
<Thread(Thread-1, started 123145413861376)> <Thread(Thread-1, started 123145413861376)>
<Thread(Thread-2, started 123145418067968)> <Thread(Thread-1, started 123145413861376)>
<Thread(Thread-2, started 123145418067968)>
<Thread(Thread-1, started 123145413861376)> <Thread(Thread-2, started 123145418067968)>
<Thread(Thread-2, started 123145418067968)>
<Thread(Thread-2, started 123145418067968)> <Thread(Thread-1, started 123145413861376)>
<Thread(Thread-2, started 123145418067968)>
<Thread(Thread-2, started 123145418067968)> <Thread(Thread-2, started 123145418067968)>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.