创建子线程
python
# 创建子线程
t1 = threading.Thread(target=job,args=(1,))
# 执行子线程
t1.start()
# 等待子线程执行
print("waiting threading")
t1.join()
print("threading done")
创建子进程
python
# 创建子进程
p1 = multiprocessing.Process(target=job,args=(1,),name="processing-1")
# 执行子进程
p1.start()
# 等待子进程执行
p1.join()
创建线程池
python
# 创建线程池
threadPool = ThreadPool(2)
start = time.time()
threadPool.map_async(func=job,iterable=(5,5,5,5))
threadPool.close()
threadPool.join()
end = time.time()
print(end-start)
创建进程池
python
# 创建进程池
threadPool = Pool(2)
start = time.time()
threadPool.map_async(func=job, iterable=(5, 5, 5, 5))
threadPool.close()
threadPool.join()
end = time.time()
print(end - start)
完整代码
python
import threading
import multiprocessing
import time
from multiprocessing.pool import ThreadPool
from multiprocessing import Pool
import os
def job(a):
time.sleep(a)
print(f"sleep: {a}")
print(f"process id is :{os.getpid()}")
def test():
# 创建子线程
t1 = threading.Thread(target=job,args=(1,))
# 执行子线程
t1.start()
print(t1.ident)
# 等待子线程执行
t1.join()
# 创建子进程
p1 = multiprocessing.Process(target=job,args=(1,),name="processing-1")
# 执行子进程
p1.start()
# 等待子进程执行
p1.join()
# 创建线程池
threadPool = ThreadPool(2)
start = time.time()
threadPool.map_async(func=job,iterable=(5,5,5,5))
threadPool.close()
threadPool.join()
end = time.time()
print(end-start)
# 创建进程池
threadPool = Pool(2)
start = time.time()
threadPool.map_async(func=job, iterable=(5, 5, 5, 5))
threadPool.close()
threadPool.join()
end = time.time()
print(end - start)
if __name__ == '__main__':
print(f"main processid {os.getpid()}")
test()
线程/进程睡眠情况下,进程池会不会新创建线程?
不会