Skip to content

Instantly share code, notes, and snippets.

@mturilin
Last active August 29, 2015 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mturilin/38415fa78fe0b445bad3 to your computer and use it in GitHub Desktop.
Save mturilin/38415fa78fe0b445bad3 to your computer and use it in GitHub Desktop.
Python multi-threading example
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)
print
message = parent_pipe.recv()
if not message:
raise RuntimeError("This is weird!")
print 'Message:', message
s = get_s()
parent_pipe.send(None)
print "Finita!"
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