Python线程、进程知识整理

一.python线程

Threading用于提供线程相关的操作,线程是应用程序中工作的最小单元。

复制代码
 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 import threading
 4 import time
 5   
 6 def show(arg):
 7     time.sleep(1)
 8     print 'thread'+str(arg)
 9   
10 for i in range(10):
11     t = threading.Thread(target=show, args=(i,))
12     t.start()
13   
14 print 'main thread stop'
复制代码

 

上述代码创建了10个“前台”线程,然后控制器就交给了CPU,CPU根据指定算法进行调度,分片执行指令。

更多方法:

  • start            线程准备就绪,等待CPU调度
  • setName      为线程设置名称
  • getName      获取线程名称
  • setDaemon   设置为后台线程或前台线程(默认)
                       如果是后台线程,主线程执行过程中,后台线程也在进行,主线程执行完毕后,后台线程不论成功与否,均停止
                        如果是前台线程,主线程执行过程中,前台线程也在进行,主线程执行完毕后,等待前台线程也执行完成后,程序停止
  • join              逐个执行每个线程,执行完毕后继续往下执行,该方法使得多线程变得无意义
  • run              线程被cpu调度后自动执行线程对象的run方法

 

复制代码
 1 import threading
 2 import time
 3  
 4  
 5 class MyThread(threading.Thread):
 6     def __init__(self,num):
 7         threading.Thread.__init__(self)
 8         self.num = num
 9  
10     def run(self):#定义每个线程要运行的函数
11  
12         print("running on number:%s" %self.num)
13  
14         time.sleep(3)
15  
16 if __name__ == '__main__':
17  
18     t1 = MyThread(1)
19     t2 = MyThread(2)
20     t1.start()
21     t2.start()
复制代码

 

二.线程锁(Lock、RLock)

由于线程之间是进行随机调度,并且每个线程可能只执行n条执行之后,当多个线程同时修改同一条数据时可能会出现脏数据,所以,出现了线程锁 - 同一时刻允许一个线程执行操作。

复制代码
 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 import threading
 4 import time
 5  
 6 gl_num = 0
 7  
 8 def show(arg):
 9     global gl_num
10     time.sleep(1)
11     gl_num +=1
12     print gl_num
13  
14 for i in range(10):
15     t = threading.Thread(target=show, args=(i,))
16     t.start()
17  
18 print 'main thread stop'
19  
20 未使用锁
复制代码

 


互斥锁 同时只允许一个线程更改数据,而Semaphore是同时允许一定数量的线程更改数据 ,比如厕所有3个坑,那最多只允许3个人上厕所,后面的人只能等里面有人出来了才能再进去。

三.信号量(Semaphore)

复制代码
 1 import threading,time
 2  
 3 def run(n):
 4     semaphore.acquire()
 5     time.sleep(1)
 6     print("run the thread: %s" %n)
 7     semaphore.release()
 8  
 9 if __name__ == '__main__':
10  
11     num= 0
12     semaphore  = threading.BoundedSemaphore(5) #最多允许5个线程同时运行
13     for i in range(20):
14         t = threading.Thread(target=run,args=(i,))
15         t.start()
复制代码

 

四.事件(event)

python线程的事件用于主线程控制其他线程的执行,事件主要提供了三个方法 set、wait、clear。

事件处理的机制:全局定义了一个“Flag”,如果“Flag”值为 False,那么当程序执行 event.wait 方法时就会阻塞,如果“Flag”值为True,那么event.wait 方法时便不再阻塞。

  • clear:将“Flag”设置为False
  • set:将“Flag”设置为True

五.条件(Condition)

使得线程等待,只有满足某条件时,才释放n个线程

复制代码
 1 def condition_func():
 2  
 3     ret = False
 4     inp = input('>>>')
 5     if inp == '1':
 6         ret = True
 7  
 8     return ret
 9  
10  
11 def run(n):
12     con.acquire()
13     con.wait_for(condition_func)
14     print("run the thread: %s" %n)
15     con.release()
16  
17 if __name__ == '__main__':
18  
19     con = threading.Condition()
20     for i in range(10):
21         t = threading.Thread(target=run, args=(i,))
22         t.start()
复制代码

 

 六.Timer

七.python进程

八.进程数据共享

进程各自持有一份数据,默认无法共享数据

复制代码
 1 #!/usr/bin/env python
 2 #coding:utf-8
 3  
 4 from multiprocessing import Process
 5 from multiprocessing import Manager
 6  
 7 import time
 8  
 9 li = []
10  
11 def foo(i):
12     li.append(i)
13     print 'say hi',li
14   
15 for i in range(10):
16     p = Process(target=foo,args=(i,))
17     p.start()
18      
19 print 'ending',li
20  
21 进程间默认无法数据共享
复制代码

 

 

1 'c': ctypes.c_char,  'u': ctypes.c_wchar,
2     'b': ctypes.c_byte,  'B': ctypes.c_ubyte,
3     'h': ctypes.c_short, 'H': ctypes.c_ushort,
4     'i': ctypes.c_int,   'I': ctypes.c_uint,
5     'l': ctypes.c_long,  'L': ctypes.c_ulong,
6     'f': ctypes.c_float, 'd': ctypes.c_double
7  
8 类型对应表

 

复制代码
 1 from multiprocessing import Process, Queue
 2  
 3 def f(i,q):
 4     print(i,q.get())
 5  
 6 if __name__ == '__main__':
 7     q = Queue()
 8  
 9     q.put("h1")
10     q.put("h2")
11     q.put("h3")
12  
13     for i in range(10):
14         p = Process(target=f, args=(i,q,))
15         p.start()
16  
17 Code
复制代码

 

当创建进程时(非使用时),共享数据会被拿到子进程中,当进程中执行完毕后,再赋值给原值。

九.进程池

进程池内部维护一个进程序列,当使用时,则去进程池中获取一个进程,如果进程池序列中没有可供使用的进进程,那么程序就会等待,直到进程池中有可用进程为止。

进程池中有两个方法:

  • apply
  • apply_async
复制代码
 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 from  multiprocessing import Process,Pool
 4 import time
 5   
 6 def Foo(i):
 7     time.sleep(2)
 8     return i+100
 9   
10 def Bar(arg):
11     print arg
12   
13 pool = Pool(5)
14 #print pool.apply(Foo,(1,))
15 #print pool.apply_async(func =Foo, args=(1,)).get()
16   
17 for i in range(10):
18     pool.apply_async(func=Foo, args=(i,),callback=Bar)
19   
20 print 'end'
21 pool.close()
22 pool.join()#进程池中进程执行完毕后再关闭,如果注释,那么程序直接关闭。
复制代码

 

posted @   24小时编程自习室  阅读(304)  评论(0)    收藏  举报
点击右上角即可分享
微信分享提示