进程和线程简单而基本靠谱的定义如下:
1. 进程:程序的一次执行
2. 线程:CPU的基本调度单位
单线程实例:
#!/usr/bin/python3
from time import ctime, sleep
#说 def talk():
print(‘Start talk: %r‘%ctime())
sleep(2)
#写 def write():
print(‘Start write: %r‘%ctime())
sleep(3)
if __name__ == ‘__main__‘:
talk()
write()
print(‘All end %r‘%ctime())
执行结果:
Start talk: ‘Sat Feb 10 17:27:45 2018‘
Start write: ‘Sat Feb 10 17:27:47 2018‘
All end ‘Sat Feb 10 17:27:50 2018‘
单线程在程序执行时,所走的程序路径按照连续顺序排下来,前面的必须处理好,后面的才会执行。
多线程:
多线程(MultiThreading)是指从软件或者硬件上实现多个线程并发执行的技术。
案例:让学生同时进行说和写操作
#!/usr/bin/python3
from time import sleep, ctime
import threading
#定义说和写的方法
def talk(content,loop):
for i in range(loop):
print(‘Start talk: %s %s‘%(content,ctime()))
sleep(2)
def write(content,loop):
for i in range(loop):
print(‘Start write: %s %s‘%(content,ctime()))
sleep(3)
#定义和加载说和写的线程
threads = [] t1 =threading.Thread(target=talk, args=(‘Hello 51zxw!‘, 2))
threads.append(t1)
t2 = threading.Thread(target=write,args=(‘Life is short you need python‘, 2))
threads.append(t2)
#执行多线程
if __name__ == ‘__main__‘:
for t in threads:
t.start()
for t in threads:
t.join()
print(‘All Thread end! %s‘%ctime())
执行结果:
Start talk: Hello 51zxw! Sat Feb 10 17:56:03 2018
Start write: Life is short you need python Sat Feb 10 17:56:03 2018
Start talk: Hello 51zxw! Sat Feb 10 17:56:05 2018
Start write: Life is short you need python Sat Feb 10 17:56:06 2018
All Thread end! Sat Feb 10 17:56:09 2018
多线程
from time import ctime, sleep
import multiprocessing
#定义两个方法说和写
def talk(content,loop):
for i in range(loop):
print(‘Talk: %s %s‘%(content,ctime()))
sleep(2)
def write(content,loop):
for i in range(loop):
print(‘Write: %s %s‘%(content,ctime()))
sleep(3)
#定义两个进程
process = []
p1 = multiprocessing.Process(target=talk, args = (‘Hello 51zxw‘, 2))
process.append(p1)
p2 = multiprocessing.Process(target=write, args=(‘Python‘, 2))
process.append(p2)
#调用进程
if __name__ == ‘__main__‘:
for p in process:
p.start()
for p in process:
p.join()
print(‘All end %s‘%ctime())
执行结果:
Talk: Hello 51zxw Sat Feb 10 18:23:46 2018
Write: Python Sat Feb 10 18:23:46 2018
Talk: Hello 51zxw Sat Feb 10 18:23:48 2018
Write: Python Sat Feb 10 18:23:49 2018
All end Sat Feb 10 18:23:52 2018
从结果分析,多进程与多线程的执行结果相似,但实现的过程却有很大的不同,不同之处还需深入了解。