1.子进程
创建进程池同时启动多个子进程
from multiprocessing import Pool
import os,time,random
#子进程要执行的代码
def long_time_task(name):
print('Run task %s (%s)...' % (name,os.getpid()))
start=time.time()
time.sleep(random.random()*3)
end=time.time()
print('Task %s runs %0.2f seconds.' % (name,(end-start)))
if __name__=='__main__':
print('Parent process %s.' % os.getpid())
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()
print('All subprocesses done.')
Parent process 6868.
Waiting for all subprocesses done...
All subprocesses done.
2.创建线程
import time,threading
#新线程执行的代码:
def loop():
print('thread %s is running...' % threading.current_thread().name)
n=0
while n<5:
n=n+1
print('thread %s >>> %s' % (threading.current_thread().name,n))
time.sleep(1)
print('thread %s ended.' % threading.current_thread().name)
print('thread %s is running...' % threading.current_thread().name)
print('thread %s is running...' % threading.current_thread().name)
t=threading.Thread(target=loop,name='LoopThread')
t.start()
t.join()
print('thread %s ended.' % threading.current_thread().name)
3.上锁
可以看做系统是随机的挑选线程执行,为了让某一段代码被一个线程从头到尾完整的执行,必须上锁
balance = 0
lock = threading.Lock()
def run_thread(n):
for i in range(100000):
# 先要获取锁:
lock.acquire()
try:
# 放心地改吧:
change_it(n)
finally:
# 改完了一定要释放锁:
lock.release()
这样,change_it函数就会被从一个线程从头到尾完整执行