目录
一 、线程
线程是进程的实际工作单位。各线程之间共享分配给进程的资源。当不同的线程需要操作共享数据时,当两个或以上对共享内存的操作发生在并发线程中,并且至少有一个可以改变数据,又没有同步机制的条件下,就会产生竞争条件,可能会导致执行无效代码、bug、或异常行为。
import threading
threading 包用于创建线程。
import threading
import time
def music(data):
print("bengin listen music: {}".format(time.ctime()))
time.sleep(2)
print(str(data))
print("music end: {}".format(time.ctime()))
def movie(data):
print("bengin look movie: {}".format(time.ctime()))
time.sleep(5)
print(str(data))
print("movie end: {}".format(time.ctime()))
thread_list = []
th1 = threading.Thread(target=music, args=("love.mp3",))
th2 = threading.Thread(target=movie, args=("Anit.avi",))
thread_list.append(th1)
thread_list.append(th2)
for th in thread_list:
th.start()
for th in thread_list:
th.join()
print("main thread continue: {}".format(time.ctime()))
二 、进程
1. 如果使用多进程就可以真正利用多核,因为各进程之间是相互独立的,不共享资源,可以在不同的核上执行不同的进程,达到并行的效果。
2. 多核CPU可以同时执行多个进程,建议有几个核创建几个进程。
多核CPU 是否能同时执行多个进程? - 知乎如果能,可以同时最多执行几个进程?https://www.zhihu.com/question/271821176
multiprocessing 包用于创建进程,引入进程池概念。
from multiprocessing import Pool
Pool类下的几种方法:
# -*- coding:utf-8 -*-
from multiprocessing import Pool as Pool
import time
import random
def func(msg):
print('msg:', msg)
sleep_num = random.randint(1, 20)
time.sleep(sleep_num)
print('end:')
return msg
if __name__ == '__main__':
# 多进程要在main 中执行,不然会报错
pool = Pool(processes=3) # 我们也可自己设置,但是要考虑自己计算机的性能
# pool = Pool() # 这个参数可以不设置,如果不设置函数会跟根据计算机的实际情况来决定要运行多少个进程
result = []
for i in range(1, 100):
msg = 'hello %d' % (i)
# 非阻塞,添加任务后立即执行,不会等待进程结束
res = pool.apply_async(func, (msg,)) # 只有apply_async可以有返回值,apply,map,imap不可以设置返回值
# 阻塞式只有apply_async可以有返回值,apply,map,imap不可以设置返回值
# res = pool.apply(func, (msg,)) # 此方式没有返回值
result.append(res)
print('Mark~~~~~~~~~~~~~~~')
pool.close() # 添加任务结束
pool.join() # 堵住主进程,调用join之前,先调用close函数,否则会出错。执行完close后不会有新的进程加入到pool,join函数等待所有子进程结束
for res in result:
print("sub_process return: ", res.get())
print('sub-process done')