线程也是实现多任务的一种方式,一个进程中,也经常需要同时做多件事,就需要同时运行多个‘子任务’,这些子任务就是线程。一个进程可以拥有多个并行的线程,其中每一个线程,共享当前进程的资源。
线程可以看出是轻量级的进程。多个线程共享内存,线程切换的开销小
进程和线程在使用上各有优缺点: 线程执行开销小, 但不利于资源的管理和保护, 而进程正相反。
在Python 程序中,可以通过“_thread”和 threading(推荐使用)这两个模块来处理线程。在 Python3 中, thread 模块已经废弃。可以使用 threading 模块代替。所以,在 Python3中不能再使用 thread 模块,但是为了兼容 Python3 以前的程序,在 Python3 中将 thread 模块重命名为“_thread”
使用_thread 模块
创建线程
当使用 thread 模块来处理线程时,可以调用里面的函数 start_new_thread()来生成一个新的线程
import _thread
import time
def fun1():
print('开始运行fun1')
time.sleep(4)
print('运行fun1结束')
def fun2():
print('开始运行fun2')
time.sleep(2)
print('运行fun2结束')
if __name__=='__main__':
print('主进程开始运行')
#启动一个线程运行函数 fun1
_thread.start_new_thread(fun1,())
#启动一个线程运行函数 fun2
_thread.start_new_thread(fun2,())
time.sleep(6)
print('主进程结束运行')
fun1和fun2谁先开始不一定
为线程传递参数
import _thread
import time
def fun1(thread_name,delay):
print('线程{0}开始运行 fun1'.format(thread_name))
time.sleep(delay)
print('线程{0}运行 fun1 结束'.format(thread_name))
def fun2(thread_name,delay):
print('线程{0}开始运行 fun2'.format(thread_name))
time.sleep(delay)
print('线程{0}运行 fun2 结束'.format(thread_name))
if __name__=='__main__':
print('开始运行')
#启动一个线程运行函数 fun1
_thread.start_new_thread(fun1,('thread-1',4))
#启动一个线程运行函数 fun2
_th