谈谈对线程与进程的理解

概念:

线程

线程(threading)是操作系统能够进行运算调度的最小单位。它被包含在进程之中,是进程中的实际运作单位。一条线程指的是进程中一个单一顺序的控制流,一个进程中可以并发多个线程,每条线程并行执行不同的任务。

进程

进程(Process)是计算机中的程序关于某数据集合上的一次运行活动,是系统进行资源分配和调度的基本单位,是操作系统结构的基础。在早期面向进程设计的计算机结构中,进程是程序的基本执行实体;在当代面向线程设计的计算机结构中,进程是线程的容器。程序是指令、数据及其组织形式的描述,进程是程序的实体。

进程与线程区别

a.地址空间和其它资源:进程间相互独立,同一进程的各线程间共享。某进程内的线程在其它进程不可见。

b.通信:进程间通信IPC,线程间可以直接读写进程数据段(如全局变量)来进行通信——需要进程同步和互斥手段的辅助,以保证数据的一致性。

c.调度和切换:线程上下文切换比进程上下文切换要快得多。

d.在多线程OS中,进程不是一个可执行的实体。

 

threading模块

直接调用

 1 import threading
 2 import time
 3 
 4 def tell(num): #定义每个线程要运行的函数
 5 
 6     print(num)
 7     time.sleep(3)
 8 
 9 if __name__ == '__main__':
10     t1 = threading.Thread(target=tell,args=(1,)) #生成一个线程实例
11     t2 = threading.Thread(target=tell,args=(2,)) #生成另一个线程实例
12     t1.start() #启动线程
13     t2.start() #启动另一个线程
14     print(t1.getName()) #获取线程名
15     print(t2.getName())
View Code

继承调用

 1 __author__ = 'thinkpad'
 2 # !/usr/bin/env python
 3 #-*- coding:utf-8 -*-
 4 
 5 import threading
 6 import time
 7 
 8 class MyThread(threading.Thread):
 9 
10     def __init__(self,num):
11         threading.Thread.__init__(self)
12         self.num = num
13     def run(self):#定义每个线程要运行的函数
14         print(self.num)
15         time.sleep(3)
16 
17 if __name__ == '__main__':
18     t1 = MyThread(1)
19     t2 = MyThread(2)
20     t1.start()
21     t2.start()
22     print(t1.getName())
23     print(t2.getName())
View Code

 互拆锁

 1 __author__ = 'thinkpad'
 2 # !/usr/bin/env python
 3 #-*- coding:utf-8 -*-
 4 import threading
 5 import time
 6 
 7 def addNum():
 8     global num #在每个线程中都获取这个全局变量
 9     print('--get num:',num )
10     time.sleep(1)
11     lock.acquire() #修改数据前加锁
12     num  -=1 #对此公共变量进行-1操作
13     lock.release() #修改后释放
14 num = 100  #设定一个共享变量
15 thread_list = []
16 
17 lock = threading.Lock() #生成全局锁
18 for i in range(100):
19     t = threading.Thread(target=addNum)
20     t.start()
21     thread_list.append(t)
22 
23 for t in thread_list: #等待所有线程执行完毕
24     t.join()
25 print('final num:', num )
View Code

 

多进程Mutiprocessing

 1 from multiprocessing import Process
 2 import time
 3 def f(name):
 4     time.sleep(2)
 5     print('hello', name)
 6 
 7 if __name__ == '__main__':
 8     for i in range(4):
 9         p = Process(target=f, args=('bob',))
10         p.start()
11         p.join()
View Code
 1 from multiprocessing import Process
 2 import os
 3 
 4 def info(title):
 5     print(title)
 6     print('module name:', __name__)
 7     print('parent process:', os.getppid())
 8     print('process id:', os.getpid())
 9     print("\n\n")
10 
11 def f(name):
12     info('\033[31;1mfunction f\033[0m')
13     print('hello', name)
14 
15 if __name__ == '__main__':
16     info('\033[32;1mmain process line\033[0m')
17     p = Process(target=f, args=('bob',))
18     p.start()
19     p.join()
View Code

 

 进程间通讯

queues

 1 from multiprocessing import Process, Queue
 2  
 3 def f(q):
 4     q.put([42, None, 'hello'])
 5  
 6 if __name__ == '__main__':
 7     q = Queue()
 8     p = Process(target=f, args=(q,))
 9     p.start()
10     print(q.get())    # prints "[42, None, 'hello']"
11     p.join()
View Code

Pipes

 1 from multiprocessing import Process, Pipe
 2 
 3 def f(conn):
 4     conn.send([42, None, 'hello'])
 5     conn.close()
 6  
 7 if __name__ == '__main__':
 8     parent_conn, child_conn = Pipe()
 9     p = Process(target=f, args=(child_conn,))
10     p.start()
11     print(parent_conn.recv())   # prints "[42, None, 'hello']"
12     p.join()
View Code

Mangager

 1 from multiprocessing import Process, Manager
 2 
 3 def f(d, l):
 4     d[1] = '1'
 5     d[2] = '2'
 6     d[0.25] = None
 7     l.append(1)
 8     print(l)
 9 
10 if __name__ == '__main__':
11     with Manager() as manager:
12         d = manager.dict()
13 
14         l = manager.list(range(5))
15         p_list = []
16         for i in range(10):
17             p = Process(target=f, args=(d, l))
18             p.start()
19             p_list.append(p)
20         for res in p_list:
21             res.join()
22 
23         print(d)
24         print(l)
View Code

进程同步

 1 from multiprocessing import Process, Lock
 2  
 3 def f(l, i):
 4     l.acquire()
 5     try:
 6         print('hello world', i)
 7     finally:
 8         l.release()
 9  
10 if __name__ == '__main__':
11     lock = Lock()
12  
13     for num in range(10):
14         Process(target=f, args=(lock, num)).start()
View Code

进程池

 1 from  multiprocessing import Process,Pool
 2 import time
 3 
 4 def Foo(i):
 5     time.sleep(2)
 6     return i+100
 7 
 8 def Bar(arg):
 9     print('-->exec done:',arg)
10 
11 pool = Pool(5)
12 
13 for i in range(10):
14     pool.apply_async(func=Foo, args=(i,),callback=Bar)
15     #pool.apply(func=Foo, args=(i,))
16 
17 print('end')
18 pool.close()
19 pool.join()#进程池中进程执行完毕后再关闭,如果注释,那么程序直接关闭。
View Code

 

 

 

 

posted on 2016-03-19 16:14  学习永远在路上  阅读(3145)  评论(0编辑  收藏  举报