之前我们学了很多进程间的通信,多进程并发等等,今天我们来学习线程,线程和进程是什么关系,进程和线程有什么相同而又有什么不同今天就来揭晓这个答案。
本篇导航:
1、何为线程
每个进程有一个地址空间,而且默认就有一个控制线程。如果把一个进程比喻为一个车间的工作过程那么线程就是车间里的一个一个流水线。
进程只是用来把资源集中到一起(进程只是一个资源单位,或者说资源集合),而线程才是cpu上的执行单位。
多线程(即多个控制线程)的概念是,在一个进程中存在多个控制线程,多个控制线程共享该进程的地址空间(资源)
创建进程的开销要远大于线程开进程相当于建一个车间,而开线程相当于建一条流水线。
2、线程和进程的区别
1.Threads share the address space of the process that created it; processes have their own address space. 2.Threads have direct access to the data segment of its process; processes have their own copy of the data segment of the parent process. 3.Threads can directly communicate with other threads of its process; processes must use interprocess communication to communicate with sibling processes. 4.New threads are easily created; new processes require duplication of the parent process. 5.Threads can exercise considerable control over threads of the same process; processes can only exercise control over child processes. 6.Changes to the main thread (cancellation, priority change, etc.) may affect the behavior of the other threads of the process; changes to the parent process does not affect child processes.
中译:
1、线程共享创建它的进程的地址空间;进程有自己的地址空间。 2、线程可以直接访问其进程的数据段;进程有它们自己的父进程数据段的副本。 3、线程可以直接与进程的其他线程通信;进程必须使用进程间通信来与兄弟进程通信。 4、新线程很容易创建;新进程需要复制父进程。 5、线程可以对同一进程的线程进行相当大的控制;进程只能对子进程执行控制。 6、对主线程的更改(取消、优先级更改等)可能会影响该进程的其他线程的行为;对父进程的更改不会影响子进程。
3、多线程的优点
多线程和多进程相同指的是,在一个进程中开启多个线程
1)多线程共享一个进程的地址空间(资源)
2) 线程比进程更轻量级,线程比进程更容易创建可撤销,在许多操作系统中,创建一个线程比创建一个进程要快10-100倍,在有大量线程需要动态和快速修改时,这一特性很有用
3) 若多个线程都是cpu密集型的,那么并不能获得性能上的增强,但是如果存在大量的计算和大量的I/O处理,拥有多个线程允许这些活动彼此重叠运行,从而会加快程序执行的速度。
4) 在多cpu系统中,为了最大限度的利用多核,可以开启多个线程,比开进程开销要小的多。(这一条并不适用于python)
1、threading模块介绍
multiprocessing模块的完全模仿了threading模块的接口,二者在使用层面,有很大的相似性,因而不再详细介绍
对multiprocessing模块也不是很熟悉的朋友可以复习一下多线程时介绍的随笔:
30、进程的基础理论,并发(multiprocessing模块):http://www.cnblogs.com/liluning/p/7419677.html
官方文档:https://docs.python.org/3/library/threading.html?highlight=threading#(英语好的可以尝试挑战)
2、开启线程的两种方式(和进程一模一样)
两种方式里我们都有开启进程的方式可以简单复习回顾
1)方式一:
from threading import Thread #from multiprocessing import Process import os def talk(): print('%s is running' %os.getpid()) if __name__ == '__main__': t=Thread(target=talk) # t=Process(target=talk) t.start() print('主',os.getpid())
2)方式二:
#开启线程 from threading import Thread import os class MyThread(Thread): def __init__(self,name): super().__init__() self.name=name def run(self): print('pid:%s name:[%s]is running' %(os.getpid(),self.name)) if __name__ == '__main__': t=MyThread('lln') t.start() print('主T',os.getpid()) #开启进程 from multiprocessing import Process import os class MyProcess(Process): def __init__(self,name): super().__init__() self.name=name def run(self): print('pid:%s name:[%s]is running' % (os.getpid(), self.name)) if __name__ == '__main__': t=MyProcess('lll') t.start() print('主P',os.getpid())
3、在一个进程下开启多个线程与在一个进程下开启多个子进程的区别
1)比较速度:(看看hello和主线程/主进程的打印速度)
from threading import Thread from multiprocessing import Process import os def work(): print('hello') if __name__ == '__main__': #在主进程下开启线程 t=Thread(target=work) t.start() print('主线程/主进程') #在主进程下开启子进程 t=Process(target=work) t.start() print('主线程/主进程')
2)pid的区别:(线程和主进程相同,子进程和主进程不同)
from threading import Thread from multiprocessing import Process import os def work(): print('我的pid:',os.getpid()) if __name__ == '__main__': #part1:在主进程下开启多个线程,每个线程都跟主进程的pid一样 t1=Thread(target=work) t2=Thread(target=work) t1.start() t2.start() print('主线程/主进程pid:',os.getpid()) #part2:开多个进程,每个进程都有不同的pid p1=Process(target=work) p2=Process(target=work) p1.start() p2.start() print('主线程/主进程pid:',os.getpid())
3)数据是否共享(线程与主进程共享数据,子进程只是将主进程拷贝过去操作的并非同一份数据)
from threading import Thread from multiprocessing import Process def work(): global n n -= 1 n = 100 #主进程数据 if __name__ == '__main__': # p=Process(target=work) # p.start() # p.join() # print('主',n) #毫无疑问子进程p已经将自己的全局的n改成了99,但改的仅仅是它自己的,查看父进程的n仍然为100 t=Thread(target=work) t.start() t.join() print('主',n) #查看结果为99,因为同一进程内的线程之间共享进程内的数据
4、练习
1)三个任务,一个接收用户输入,一个将用户输入的内容格式化成大写,一个将格式化后的结果存入文件
from threading import Thread msg = [] msg_fort = [] def Inp(): while True : msg_l = input('>>:') if not msg_l : continue msg.append(msg_l) def Fort(): while True : if msg : res = msg.pop() msg_fort.append(res.upper()) def Save(): with open('db.txt','a') as f : while True : if msg_fort : f.write('%s\n' %msg_fort.pop()) f.flush() #强制将缓冲区中的数据发送出去,不必等到缓冲区满 if __name__ == '__main__': p1 = Thread(target=Inp) p2 = Thread(target=Fort) p3 = Thread(target=Save) p1.start() p2.start() p3.start()
2)将前面随笔中的服务端客户端例子用多线程实现(不了解的可以翻阅前几篇随笔)
from threading import Thread from socket import * s=socket(AF_INET,SOCK_STREAM) s.bind(('127.0.0.1',8080)) s.listen(5) def action(conn): while True: data=conn.recv(1024) print(data) conn.send(data.upper()) if __name__ == '__main__': while True: conn,addr=s.accept() p=Thread(target=action,args=(conn,)) p.start()