Last active
January 25, 2019 20:49
-
-
Save loisaidasam/34446954bddb67fcf6435179f6b89576 to your computer and use it in GitHub Desktop.
Examining shared mutable objects in threading
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ 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