线程简述
一个程序运行起来后,一定有一个执行代码的东西,这个东西就是线程;
一般计算(CPU)密集型任务适合多进程,IO密集型任务适合多线程;
一个进程可拥有多个并行的(concurrent)线程,当中每一个线程,共享当前进程的资源
以下是对发现的几种多线程进行的汇总整理,均已测试运行
多线程实现的四种方式分别是:
multiprocessing下面有两种:
1 2 3
| from multiprocessing.dummy import Pool as ThreadPool
from multiprocessing.pool import ThreadPool
|
另外两种:
1 2 3
| from concurrent.futures import ThreadPoolExecutor
import threadpool
|
方式1 multiprocessing.dummy Pool()
非阻塞方法
multiprocessing.dummy.Pool.apply_async() 和 multiprocessing.dummy.Pool.imap()
线程并发执行
阻塞方法
multiprocessing.dummy.Pool.apply()和 multiprocessing.dummy.Pool.map()
线程顺序执行
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| from multiprocessing.dummy import Pool as Pool import time
def func(msg): print('msg:', msg) time.sleep(2) print('end:') pool = Pool(processes=3) for i in range(1, 5): msg = 'hello %d' % (i) pool.apply_async(func, (msg,))
print('Mark~~~~~~~~~~~~~~~') pool.close() pool.join() print('sub-process done')
|
方式2:multiprocessing.pool ThreadPool Threading()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| from multiprocessing.pool import ThreadPool from multiprocessing.dummy import Pool as ThreadPool import os import time
print("hi outside of main()")
def hello(x): print("inside hello()") print("Proccess id: %s" %(os.getpid())) time.sleep(3) return x*x
if __name__ == "__main__": p = ThreadPool(5) pool_output = p.map(hello, range(3)) print(pool_output)
|
方式3:主流ThreadPoolExecutor
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| from concurrent.futures import ThreadPoolExecutor import threading import time
def action(max): my_sum = 0 for i in range(max): print(threading.current_thread().name + ' ' + str(i)) my_sum += i return my_sum
pool = ThreadPoolExecutor(max_workers=2)
future1 = pool.submit(action, 20)
future2 = pool.submit(action, 30)
print(future1.done()) time.sleep(3)
print(future2.done())
print(future1.result())
print(future2.result())
pool.shutdown()
|
方式4:threadpool
需要 pip install threadpool
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| import threadpool
def hello(m, n, o): """""" print("m = %s, n = %s, o = %s" % (m, n, o))
if __name__ == '__main__': dict_vars_1 = {'m': '1', 'n': '2', 'o': '3'} dict_vars_2 = {'m': '4', 'n': '5', 'o': '6'} func_var = [(None, dict_vars_1), (None, dict_vars_2)] pool = threadpool.ThreadPool(2) requests = threadpool.makeRequests(hello, func_var) [pool.putRequest(req) for req in requests] pool.wait()
""" [pool.putRequest(req) for req in requests]等同于 for req in requests: pool.putRequest(req) """
|