mirror of
https://github.com/autistic-symposium/web3-starter-py.git
synced 2025-05-17 14:10:21 -04:00
add some multiprocess and race condition examples
This commit is contained in:
parent
5224dc91ca
commit
be98abd3b5
4 changed files with 57 additions and 4 deletions
39
Concurrence_examples/daemon_example.py
Normal file
39
Concurrence_examples/daemon_example.py
Normal file
|
@ -0,0 +1,39 @@
|
|||
#!/usr/bin/env python3
|
||||
|
||||
import time
|
||||
import sys
|
||||
import multiprocessing
|
||||
|
||||
|
||||
def daemon():
|
||||
p = multiprocessing.current_process()
|
||||
|
||||
print('Starting: {}, {}'.format(p.name, p.pid))
|
||||
sys.stdout.flush()
|
||||
time.sleep(2)
|
||||
print('Exiting : {}, {}'.format(p.name, p.pid))
|
||||
|
||||
sys.stdout.flush()
|
||||
|
||||
|
||||
def non_daemon():
|
||||
p = multiprocessing.current_process()
|
||||
|
||||
print('Starting: {}, {}'.format(p.name, p.pid))
|
||||
sys.stdout.flush()
|
||||
print('Exiting : {}, {}'.format(p.name, p.pid))
|
||||
|
||||
sys.stdout.flush()
|
||||
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
d = multiprocessing.Process(name='daemon', target=daemon)
|
||||
d.daemon = True
|
||||
|
||||
n = multiprocessing.Process(name='non-daemon', target=non_daemon)
|
||||
n.daemon = False
|
||||
|
||||
d.start()
|
||||
time.sleep(1)
|
||||
n.start()
|
15
Concurrence_examples/logging_example.py
Normal file
15
Concurrence_examples/logging_example.py
Normal file
|
@ -0,0 +1,15 @@
|
|||
#!/usr/bin/env python3
|
||||
|
||||
import multiprocessing
|
||||
import logging
|
||||
import sys
|
||||
|
||||
def worker():
|
||||
print 'Doing some work'
|
||||
sys.stdout.flush()
|
||||
|
||||
if __name__ == '__main__':
|
||||
multiprocessing.log_to_stderr(logging.DEBUG)
|
||||
p = multiprocessing.Process(target=worker)
|
||||
p.start()
|
||||
p.join()
|
|
@ -3,17 +3,16 @@
|
|||
import threading
|
||||
|
||||
x = 0
|
||||
|
||||
COUNT = 10000000
|
||||
|
||||
def foo():
|
||||
global x
|
||||
for i in xrange(COUNT):
|
||||
for i in range(COUNT):
|
||||
x += 1
|
||||
|
||||
def bar():
|
||||
global x
|
||||
for i in xrange(COUNT):
|
||||
for i in range(COUNT):
|
||||
x -= 1
|
||||
|
||||
t1 = threading.Thread(target=foo)
|
||||
|
|
|
@ -8,7 +8,7 @@ import threading
|
|||
def worker(n):
|
||||
sleep = random.randrange(1, 10)
|
||||
time.sleep(sleep)
|
||||
print("Worker {}: sleeping for {} seconds.".format(n, sleep))
|
||||
print("Worker {} from {}: sleeping for {} seconds.".format(n, threading.get_ident(), sleep))
|
||||
|
||||
|
||||
for i in range(5):
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue