一、什么是线程,什么是进程
首先,线程和进程都是一个时间段的描述,是cpu工作时间段的描述。
线程是程序执行流的最小单元,线程有就绪,阻塞和运行三种状态,就绪就是指线程具备所有的运行条件,逻辑上可以运行,只需等待cpu分配时间片即可,运行状态就是指线程占有cpu时间片,正在运行,阻塞是指线程在等待一个事件(如某个信号量),逻辑上不可执行,每一个程序至少有一个线程。线程是程序中一个单一的顺讯控制流程,进程内有一个相对独立的、可调度的执行单元,是系统独立调度和分派cpu的基本单位指令运行时的调度单位,在单个程序中同时运行多个线程完成不同的工左,称为多线程
进程是cpu分配资源的最小单位,也有就绪,运行,阻塞三种状态。
二,python多线程
1、使用_thread模块创建两个线程
import time
import _thread
def function_one():
for i in range(5):
time.sleep(1)
print('function_one run')
def function_two():
for i in range(5):
time.sleep(1)
print('function_two run')
def main():
#创建两个线程
try:
thread1 = _thread.start_new_thread(function_one,())
thread2 =_thread.start_new_thread(function_two,())
except Exception as Erorr:
print(Erorr)
else:
print('线程创建成功')
time.sleep(10)
if __name__ == '__main__':
main()
2、使用threading模块创建两个线程
import time
import threading
def function(times):
for i in range(6):
time.sleep(1)
print('function_%s run %s'%(times,i))
def main():
#创建两个线程
try:
t1 = threading.Thread(target=function,args=('one',))
t2 = threading.Thread(target=function,args=('two',))
except Exception as Erorr:
print(Erorr)
else: