python代码(7.18-7.24)总结

一、线程池开发总结

1、Queue模块原理

    1)生产者消费者模型 数据结构为队列

  2)实例创建即产生新的队列 与全局无关

#! /usr/bin/env python

import threading
import Queue
import time
class ThreadPool:
    
    def __init__(self,num = 20):
        self.que = Queue.Queue(num)
        for i in xrange(num):
            self.que.put(threading.Thread)
        #self.que.put(threading.Thread)
    def get_thd(self):
        return self.que.get()
    def put_thd(self):
        self.que.put(threading.Thread)
    def thd_count(self):
        return self.que.qsize()
    def full_thd(self):
        return self.que.full()

def Foo(parameter):
    time.sleep(1)
    print parameter*100
    
        
thdp = ThreadPool()
thdp_count = thdp.thd_count()
print thdp_count

rt = thdp.get_thd()
print id(rt)
rt(target = Foo,args = (1,))
thdp_count = thdp.thd_count()
print thdp_count


rt = thdp.get_thd()
print id(rt)
rt(target = Foo,args = (1,))
thdp_count = thdp.thd_count()
print thdp_count

fullthd = thdp.full_thd()
print fullthd

thdp_count = thdp.thd_count()
print thdp_count

  

2、q.full()和empty方法

 返回True和False

3、主线程是否等子线程

即 就是线程是否快速结束

t.setDaemon(False) 不快速  等

4、线程中 join

1)主线程等待,子线程执行。

2)join(2)  含义为 最多等待两秒。  比如线程执行要3秒,那么在等待两秒后将不再等待继续执行,若程序是1秒,则等待一秒后继续执行。

5、线程终止和释放

 1 #! /usr/bin/env python
 2 
 3 import threading
 4 import time
 5 
 6 
 7 def Foo(eve):
 8     print 'start'
 9     eve.wait()
10     print 'execut'
11 
12 
13 eve_obj = threading.Event()
14 for i in xrange(10):
15     rt = threading.Thread(target = Foo,args = (eve_obj,))
16     rt.start()
17 
18 #eve_obj.clear()
19 inp = raw_input('input')
20 if inp:
21     eve_obj.set()
View Code

 

posted on 2016-07-24 10:27  lexn  阅读(105)  评论(0)    收藏  举报

导航