python 线程与进程

进程(Process)

是计算机中的程序关于某数据集合上的一次运行活动,是系统进行资源分配和调度的基本单位,是操作系统结构的基础。

线程(Thread)

有时被称为轻量级进程(Lightweight Process,LWP),是程序执行流的最小单元。 线程是进程中的一个实体,是被系统独立调度和分派的基本单位,一个进程可以包含多个线程,但是线程不能包含多个进程线程自己不拥有系统资源 ,在单个程序中同时运行多个线程完成不同的工作,称为多线程。

线程与进程的区别

线程和进程的区别在于,子进程和父进程有不同的代码和数据空间,而多个线程则共享数据空间,每个线程有自己的执行堆栈和程序计数器为其执行上下文

Tips

LoadRunner和Jmeter性能测试工具也利用了多线程和多进程来构造多个并发用户来执行性能测试

线程与进程图文解释

http://www.ruanyifeng.com/blog/2013/04/processes_and_threads.html


单线程

单线程在程序执行时,所走的程序路径按照连续顺序排下来,前面的必须处理好,后面的才会执行

案例:一个学生先用2秒说话,接着用3秒写字,最后结束

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())

if __name__=="__main__": 表示如果当前模块是被直接运行的,则该语句之后代码块被运行,如果模块是被导入的,则代码块不被运行

运行结果:

Start talk: 'Mon Dec 18 15:52:31 2017'
Start write: 'Mon Dec 18 15:52:33 2017'
All end ! 'Mon Dec 18 15:52:36 2017'

多线程

多线程(MultiThreading)是指从软件或者硬件上实现多个线程并发执行的技术

案例:让学生同时进行说和写操作

from time import ctime,sleep
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 Python!",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 ! %r" %ctime())

运行结果:

Start talk Hello Python! Mon Dec 18 15:56:06 2017
Start write Life is short,you need python! Mon Dec 18 15:56:06 2017
Start talk Hello Python! Mon Dec 18 15:56:08 2017
Start write Life is short,you need python! Mon Dec 18 15:56:09 2017
All thread end ! 'Mon Dec 18 15:56:12 2017'


 

优化线程的创建

从上面的例子中发现线程的创建时颇为麻烦的,每创建一个线程都需要创建一个t(t1、t2、...),当创建的线程较多时这样及其不方便。下面对例子进行改进

from time import sleep,ctime
import threading
#创建超级学生
def super_student(file_,time):
    for i in range(2):
        print('start %s! %s' %(file_,ctime()))
        sleep(time)
#说、写的文字和时长
lists={'Talk:hello python':2,'Write:life is short,I need python':3,'Write:Hahaha':5}
threads=[]
files=range(len(lists))
#创建线程
for i,j in lists.items():
    t=threading.Thread(target=super_student,args=(i,j))
    threads.append(t)
if __name__=='__main__':
    for t in files:
        threads[t].start()
    for t in files:
        threads[t].join()
    print('all end!%s' %(ctime()))

我们对说和写功能也做了增强。首先,创建了一个super_student()函数,这个函数可以接收操作(说、写)和时长,可以做任何动作。

然后我们创建了一个lists字典用于存放操作名与时长,通过for循环读取字典,并调用super_student()函数创建字典,接着将创建的字典都追加到threads数组中。

最后,通过循环启动线程数组threads中的线程,运行结果如下:

start Talk:hello python! Mon Dec 18 16:14:35 2017
start Write:life is short,I need python! Mon Dec 18 16:14:35 2017
start Write:Hahaha! Mon Dec 18 16:14:35 2017
start Talk:hello python! Mon Dec 18 16:14:37 2017
start Write:life is short,I need python! Mon Dec 18 16:14:38 2017
start Write:Hahaha! Mon Dec 18 16:14:40 2017
all end!Mon Dec 18 16:14:45 2017


 

多进程

与多线程相比,多进程就是import multiprocessing 然后替换相应的方法multiprocessing.Process()

案例

from time import ctime,sleep
import multiprocessing
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)
process=[]
p1=multiprocessing.Process(target=talk,args=("hello python",2))
process.append(p1)
p2=multiprocessing.Process(target=write,args=("Life is short,you need python!",2))
process.append(p2)
if __name__=='__main__':
    for p in process:
        p.start()
    for p in process:
        p.join()
    print("All process end ! %s" %ctime())

运行结果:

Start talk hello python Mon Dec 18 16:00:11 2017
Start write Life is short,you need python! Mon Dec 18 16:00:11 2017
Start talk hello python Mon Dec 18 16:00:13 2017
Start write Life is short,you need python! Mon Dec 18 16:00:14 2017
All process end ! Mon Dec 18 16:00:17 2017

原文地址:https://www.cnblogs.com/NancyRM/p/8058579.html