标签:python concurrency 多进程
from multiprocessing import Process import os import time def sleeper(name, seconds): print "Process ID# %s" % (os.getpid()) print "Parent Process ID# %s" % (os.getppid()) print "%s will sleep for %s seconds" % (name, seconds) time.sleep(seconds) if __name__ == "__main__": child_proc = Process(target=sleeper, args=('bob', 5)) child_proc.start() print "in parent process after child process start" print "parent process abount to join child process" child_proc.join() print "in parent process after child process join" print "the parent's parent process: %s" % (os.getppid())
from multiprocessing import Process, Queue def offer(queue): queue.put("Hello World") def test(queue, num): queue.put("Hello World: " + str(num)) if __name__ == '__main__': q = Queue() p1 = Process(target=test, args=(q, 1)) p1.start() p = Process(target=offer, args=(q,)) p.start() p2 = Process(target=test, args=(q, 2)) p2.start() p2 = Process(target=test, args=(q, 3)) p2.start() print q.get() print q.get() print q.get() print q.get() print q.close()输出:
from multiprocessing import Process, Pipe def send(conn): conn.send("Hello World") conn.close() if __name__ == '__main__': parent_conn, child_conn = Pipe() p = Process(target=send, args=(child_conn,)) p.start() print parent_conn.recv()
from multiprocessing import Process, Lock def l(lock, num): lock.acquire() print "Hello Num: %s" % (num) lock.release() if __name__ == '__main__': lock = Lock() for num in range(20): Process(target=l, args=(lock, num)).start()
标签:python concurrency 多进程
原文地址:http://blog.csdn.net/offbye/article/details/38731363