Last active
August 29, 2015 14:00
-
-
Save mturilin/38415fa78fe0b445bad3 to your computer and use it in GitHub Desktop.
Python multi-threading example
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
from multiprocessing import Process, Pipe | |
import sys | |
import time | |
import random | |
def worker(p): | |
while True: | |
s = p.recv() | |
if not s: | |
break | |
time.sleep(random.random()) | |
p.send("%s is a %s!" % (s, random.choice(['cat', 'dog', 'oter', 'hedgehog']))) | |
def get_s(): | |
return raw_input("Enter a name: ") | |
parent_pipe, child_pipe = Pipe() | |
p = Process(target=worker, args=[child_pipe]) | |
p.start() | |
s = get_s() | |
while s: | |
parent_pipe.send(s) | |
print 'Thinking', | |
while not parent_pipe.poll(): | |
print '.', | |
sys.stdout.flush() | |
time.sleep(.1) | |
message = parent_pipe.recv() | |
if not message: | |
raise RuntimeError("This is weird!") | |
print 'Message:', message | |
s = get_s() | |
parent_pipe.send(None) | |
print "Finita!" |
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
from multiprocessing import Process, Queue | |
import sys | |
import time | |
import random | |
def worker(s_q, r_q): | |
while True: | |
s = s_q.get() | |
if not s: | |
break | |
time.sleep(random.random()) | |
r_q.put("%s is a %s!" % (s, random.choice(['cat', 'dog', 'oter', 'hedgehog']))) | |
def get_s(): | |
return raw_input("Enter a name: ") | |
send_q = Queue() | |
receive_q = Queue() | |
p = Process(target=worker, args=[send_q, receive_q]) | |
p.start() | |
s = get_s() | |
while s: | |
send_q.put(s) | |
while receive_q.empty(): | |
print '.', | |
sys.stdout.flush() | |
time.sleep(.2) | |
message = receive_q.get_nowait() | |
if not message: | |
raise RuntimeError("This is weird!") | |
print 'Message:', message | |
s = get_s() | |
send_q.put(None) | |
print "Finita!" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment