1. 多线程的理解
多进程和多线程都可以执行多个任务,线程是进程的一部分。线程的特点是线程之间可以共享内存和变量,资源消耗少,缺点是线程之间的同步和加锁比较麻烦(未考虑)。
2. 举例
python中,有两个标准模块thread和threading可以实现多线程,不过threading更加高级,下面就threading举例。
#-*- coding:utf-8 -*-
import threading
import time
def target():
print("the current threading %s is runing"(threading.current_thread().name))
time.sleep(1)
print("the current threading %s is ended"%(threading.current_thread().name))
print("the current threading %s is runing"%(threading.current_thread().name))
## 属于线程t的部分
t = threading.Thread(target=target)
t.start()
## 属于线程t的部分
t.join() # join是阻塞当前线程(此处的当前线程时主线程) 主线程直到Thread-1结束之后才结束
print("the current threading %s is ended"%(threading.current_thread().name))
start是启动线程,join是阻塞当前线程
Python中,默认情况下,如果不加join语句,那么主线程不会等到当前线程结束才结束,但却不会立即杀死该线程。
#-*- coding:utf-8 -*-
## Python中,默认情况下,如果不加join语句,那么主线程不会等到当前线程结束才结束,但却不会立即杀死该线程。
## 这个时候,主线程会先执行,然后结束,之后子线程才会结束。
import threading
import time
def target():
print("the current threading %s is runing"%(threading.current_thread().name))
time.sleep(1)
print("the current threading %s is ended"%(threading.current_thread().name))
print("the current threading %s is runing"%(threading.current_thread().name))
## 属于线程t的部分
t = threading.Thread(target=target)
t.start()
## 属于线程t的部分
print("the current threading %s is ended"%(threading.current_thread().name))
输出如下:
the curent threading MainThread is running
the curent threading Thread-1 is running
the curent threading MainThread is ended
the curent threading Thread-1 is ended
但如果为线程实例添加t.setDaemon(True)之后,如果不加join语句,那么当主线程结束之后,会杀死子线程。
#-*- coding:utf-8 -*-
## 为线程实例添加t.setDaemon(True)之后,如果不加join语句,那么当主线程结束之后,会杀死子线程。
## 加上join之后,可以设置等待时间,表示等待线程一段时间后再退出。如果join()中不加时间,则主
## 线程会一直等待,直到子线程结束
import threading
import time
def target():
print 'the curent threading %s is running' % threading.current_thread().name
time.sleep(4)
print 'the curent threading %s is ended' % threading.current_thread().name
print 'the curent threading %s is running' % threading.current_thread().name
t = threading.Thread(target=target)
t.setDaemon(True)
t.start(1) # 等待一秒
# t.join()
print 'the curent threading %s is ended' % threading.current_thread().name
因为python语言是解释型语言,多线程并不能真正的发挥作用,因为在Python中,有一个GIL,即全局解释锁,该锁的存在保证在同一个时间只能有一个线程执行任务,也就是多线程并不是真正的并发,只是交替得执行。
但是,当程序中涉及到IO密集型任务,比如说往磁盘中读取数据,一个任务阻塞在IO操作上时,我们可以立即切换执行其他线程上执行其他IO操作请求。
第一次尝试多线程是当时想用两个线程来处理opencv的显示问题。
然后第二次就是在项目中对视频的解码,和存图片创建多个线程进行处理。
在caffe中,使用transform类进行resize处理速度比直接调用opencv的resize函数进行处理速度会慢很多