接着上篇继续跟着沫凡小哥学 Python 啦
1.1 什么是多线程 Threading
多线程可简单理解为同时执行多个任务。
多进程和多线程都可以执行多个任务,线程是进程的一部分。线程的特点是线程之间可以共享内存和变量,资源消耗少(不过在 Unix 环境中,多进程和多线程资源调度消耗差距不明显,Unix 调度较快),缺点是线程之间的同步和加锁比较麻烦。
1.2 添加线程 Thread
导入模块
- import threading
获取已激活的线程数
- threading.active_count()
查看所有线程信息
- threading.enumerate()
查看现在正在运行的线程
- threading.current_thread()
添加线程,
接收参数
- threading.Thread()
代表这个线程要完成的任务,需自行定义
- target
- def thread_job():
- print('This is a thread of %s' % threading.current_thread())
- def main():
- thread = threading.Thread(target=thread_job,) # 定义线程
- thread.start() # 让线程开始工作
- if __name__ == '__main__':
- main()
1.3 join 功能
因为线程是同时进行的,使用 join 功能可让线程完成后再进行下一步操作,即阻塞调用线程,直到队列中的所有任务被处理掉。
- import threading
- import time
- def thread_job():
- print('T1 start\n')
- for i in range(10):
- time.sleep(0.1)
- print('T1 finish\n')
- def T2_job():
- print('T2 start\n')
- print('T2 finish\n')
- def main():
- added_thread=threading.Thread(target=thread_job,name='T1')
- thread2=threading.Thread(target=T2_job,name='T2')
- added_thread.start()
- #added_thread.join()
- thread2.start()
- #thread2.join()
- print('all done\n')
- if __name__=='__main__':
- main()
例子如上所示,当不使用 join 功能的时候,结果如下图所示:
当执行了 join 功能之后,T1 运行完之后才运行 T2,之后再运行 print('all done')
1.4 储存进程结果 queue
queue 是 python 标准库中的线程安全的队列(FIFO)实现, 提供了一个适用于多线程编程的先进先出的数据结构,即队列,用来在生产者和消费者线程之间的信息传递
(1)基本 FIFO 队列
class queue.Queue(maxsize=0)
maxsize 是整数,表明队列中能存放的数据个数的上限,达到上限时,插入会导致阻塞,直至队列中的数据被消费掉,如果 maxsize 小于或者等于 0,队列大小没有限制
(2)LIFO 队列 last in first out 后进先出
class queue.LifoQueue(maxsize=0)
(3)优先级队列
class queue.PriorityQueue(maxsize=0)
视频中的代码,看的还不是特别明白
- import threading
- import time
- from queue import Queue
- def job(l,q):
- for i in range(len(l)):
- l[i]=l[i]**2
- q.put(l)
- def multithreading():
- q=Queue()
- threads=[]
- data=[[1,2,3],[3,4,5],[4,5,6],[5,6,7]]
- for i in range(4):
- t=threading.Thread(target=job,args=(data[i],q))
- t.start()
- threads.append(t)
- for thread in threads:
- thread.join()
- results=[]
- for _ in range(4):
- results.append(q.get())
- print(results)
- if __name__=='__main__':
- multithreading()
运行结果如下所示
来源: http://www.cnblogs.com/wwf828/p/7282123.html