1. 创建线程
-
使用 os 下的 fork() 函数调用(仅限 Unix 系统)
import os
print('current process (%s) starts ...' % (os.getpid()))
pid = os.fork()
if pid < 0:
print('fork error.')
elif pid == 0:
print('now i am the child process (%s)' % (os.getpid()))
# 函数执行到这里时,是离开父进程的上下文,进入子进程的上下文,因此此时 os.getpid() 是子进程的进程号;
else:
print('i (%s) created the child process (%s)' % (os.getpid(), pid))
# 子进程调用结束,返回父进程 # 完整的执行顺序是这样的,父进程 => 子进程 => 父进程 -
multiprocessing 使用 Process 类创建进程对象:
from multiprocessing import Process
def run_proc(name):
print('Child process %s (%s)' % (name, os.getpid())) print('Current process (%s).' % (os.getpid()))
for i in range(5):
p = Process(target=run_proc, args=(str(i), ))
p.start()
p.join()
2. 注意进程(process)和线程(thread)的区别
Python标准库10 多进程初步 (multiprocessing包)
python 中创建进程使用 multiprocessing 库,创建线程则是 threading 库,二者的区别在于,如下例所示:
import os
import threading
import multiprocessing
def worker(sign, lock):
lock.acquire()
print(sign, os.getpid())
lock.release()
print('Main: ', os.getpid())
record = []
lock = threading.Lock()
for i in range(5):
thread = threading.Thread(target=worker, args=(" threading %s" % i, lock))
thread.start()
record.append(thread)
for thread in record:
thread.join()
record = []
lock = multiprocessing.Lock()
for i in range(5):
process = multiprocessing.Process(target=worker, args=(' processing %s'%i, lock))
process.start()
record.append(process)
for process in record:
process.join()
所有Thread的PID都与主程序相同,而每个Process都有一个不同的PID。