add mure concurrence examples

This commit is contained in:
Mia von Steinkirch 2020-03-03 19:51:03 -08:00
parent f35541a061
commit 2333b724ec
3 changed files with 54 additions and 0 deletions

View file

@ -0,0 +1,14 @@
import multiprocessing
import time
import random
def worker(n):
sleep = random.randrange(1, 10)
time.sleep(sleep)
print("Worker {}: sleeping for {} seconds.".format(n, sleep))
for i in range(5):
t = multiprocessing.Process(target=worker, args=(i,))
t.start()

View file

@ -0,0 +1,26 @@
import threading
x = 0
COUNT = 10000000
def foo():
global x
for i in xrange(COUNT):
x += 1
def bar():
global x
for i in xrange(COUNT):
x -= 1
t1 = threading.Thread(target=foo)
t2 = threading.Thread(target=bar)
t1.start()
t2.start()
t1.join()
t2.join()
print(x)

View file

@ -0,0 +1,14 @@
import time
import random
import threading
def worker(n):
sleep = random.randrange(1, 10)
time.sleep(sleep)
print("Worker {}: sleeping for {} seconds.".format(n, sleep))
for i in range(5):
t = threading.Thread(target=worker, args=(i,))
t.start()