from multiprocessing import Process p = Process(target=run_proc, args=('test',)) p.start() p.join() from multiprocessing import Pool p = Pool(4) for i in range(5): p.apply_async(long_time_task, args=(i,)) print('Waiting for all subprocesses done...') p.close() p.join() 进程间通信 Queue、Pipes
from multiprocessing import Process, Queue import os, time, random
# 写数据进程执行的代码: def write(q): print('Process to write: %s' % os.getpid()) for value in ['A', 'B', 'C']: print('Put %s to queue...' % value) q.put(value) time.sleep(random.random())
# 读数据进程执行的代码: def read(q): print('Process to read: %s' % os.getpid()) while True: value = q.get(True) print('Get %s from queue.' % value)
Process to write: 50563 Put A to queue... Process to read: 50564 Get A from queue. Put B to queue... Get B from queue. Put C to queue... Get C from queue.
线程
1 2 3 4 5
import time, threading
t = threading.Thread(target=loop, name='LoopThread') t.start() t.join()
def consumer(): r = '' while True: n = yield r if not n: return print('[CONSUMER] Consuming %s...' % n) r = '200 OK'
def produce(c): c.send(None) n = 0 while n < 5: n = n + 1 print('[PRODUCER] Producing %s...' % n) r = c.send(n) print('[PRODUCER] Consumer return: %s' % r) c.close()
c = consumer() produce(c)
aiohttp
分布式进程
1
from multiprocessing.managers import BaseManager
多进程和多线程java
创建新线程
1 2 3 4 5 6 7 8 9 10
Thread t = new MyThread(); t.start(); // 启动新线程 Thread t = new Thread(new MyRunnable()); t.start(); // 启动新线程
Thread t = new Thread(() -> { System.out.println("start new thread!"); }); t.start(); // 启动新线程
// 多线程 public class Main { public static void main(String[] args) throws Exception { var add = new AddThread(); var dec = new DecThread(); add.start(); dec.start(); add.join(); dec.join(); System.out.println(Counter.count); } }
class Counter { public static final Object lock = new Object(); public static int count = 0; }
class AddThread extends Thread { public void run() { for (int i=0; i<10000; i++) { synchronized(Counter.lock) { Counter.count += 1; } } } }
class DecThread extends Thread { public void run() { for (int i=0; i<10000; i++) { synchronized(Counter.lock) { Counter.count -= 1; } } } }