Python练习代码 -- 线程创建, 同步

来源:互联网 发布:周扬青淘宝店 卖什么 编辑:程序博客网 时间:2024/06/02 11:27

1. 创建线程

# -*- mode: python; coding: utf-8 -*-import threadimport timeimport threadingimport randomdef worker(index, create_time):    print("sub thread %d \n" %(index))#创建线程方法1 thread modulefor index in range(5):    thread.start_new_thread(worker, (index, time.time()))time.sleep(3)#创建线程方法2 threading moduleclass MyThread1(threading.Thread):    def __init__(self, index):        super(MyThread1,self).__init__()        self.index = index    def run(self):        time.sleep(1)        print("this is mythread: %d\n" %(self.index))threads = []for index in range(5):    mythread1 = MyThread1(index)    mythread1.start()    threads.append(mythread1)#主线程等待 5sfor t in threads:    t.join(5)#threadlocal  线程局部变量class ThreadLocal(threading.Thread):    def __init__(self):        super(ThreadLocal, self).__init__()        self.local = threading.local()    def run(self):        time.sleep(random.random())                     self.local.number = []        for i in range(10):            self.local.number.append( random.choice(range(10)) )        print(threading.currentThread(), self.local.number, )                           threads2 = []for i in range(5):    t = ThreadLocal()    t.start()    threads2.append(t)for t in threads2:    t.join(1) print("Main thread exit...")

2. 锁机制

# -*- mode: python; coding: utf-8 -*-import threadingimport timeimport randomclass Counter(object):    def __init__(self):        self.value = 0        self.lock = threading.Lock()    def add(self):        self.lock.acquire()        self.value += 1                value = self.value        time.sleep( random.random() )          print(value)        self.lock.release()        return valuecounter = Counter()class Thread1(threading.Thread):    def __init__(self, index):        super(Thread1, self).__init__()        self.index = index            def run(self):                                counter.add()                 threads1 = []    for i in range(10):    t = Thread1(i)    t.start()        for t in threads1:    t.join()        

3. 条件变量

# -*- mode: python; coding: utf-8 -*-from threading import Thread, Condition, currentThreadimport timeclass Goods: #产品类    def __init__(self): #初始化函数        self.count=0    def produce(self,num=1): #产品增长        self.count += num    def consume(self): #产品减少        if self.count:            self.count -= 1    def isEmpty(self): #判断产品是否为空        return not self.countclass Producer(Thread): #生产者类    def __init__(self,condition,goods,sleeptime=4):        Thread.__init__(self)        self.cond=condition        self.goods=goods        self.sleeptime=sleeptime    def run(self):        cond=self.cond        goods=self.goods        while 1 :             cond.acquire()             goods.produce()            print ("Goods Count: ", goods.count, "Producer thread produced ")            cond.notifyAll() #通知满足此条件变量的线程            cond.release()            time.sleep(self.sleeptime)class Consumer(Thread): #消费者类    def __init__(self,index, condition,goods,sleeptime=1):        Thread.__init__(self, name = str(index))        self.cond=condition        self.goods=goods        self.sleeptime=sleeptime    def run(self):        cond=self.cond        goods=self.goods        while 1:            time.sleep(self.sleeptime)            cond.acquire()             while goods.isEmpty():                cond.wait() #如果为空,则等待            goods.consume()            print ("Goods Count: ", goods.count, "Consumer thread",currentThread().getName(),"consumed ")            cond.release()         goods=Goods()cond=Condition()producer=Producer(cond,goods)producer.start() #启动生产者线程for i in range(5):    consumer = Consumer(i,cond,goods)    consumer.start() #启动5个消费者线程    consumer.join()

4. 同步队列

我们经常会采用生产者/消费者关系的两个线程来处理一个共享缓冲区的数据。例如一个生产者线程接受用户数据放入一个共享缓冲区里,等待一个消费者线程对数据取出处理。但是如果缓冲区的太小而生产者和消费者两个异步线程的速度不同时,容易出现一个线程等待另一个情况。为了尽可能的缩短共享资源并以相同速度工作的各线程的等待时间,我们可以使用一个“队列”来提供额外的缓冲区。

    创建一个“队列”对象

    import Queue
    myqueue = Queue.Queue(maxsize = 10)

    Queue.Queue类即是一个队列的同步实现。队列长度可为无限或者有限。可通过Queue的构造函数的可选参数maxsize来设定队列长度。如果maxsize小于1就表示队列长度无限。

    将一个值放入队列中

    myqueue.put(10)

    调用队列对象的put()方法在队尾插入一个项目。put()有两个参数,第一个item为必需的,为插入项目的值;第二个block为可选参数,默认为1。如果队列当前为空且block1put()方法就使调用线程暂停,直到空出一个数据单元。如果block0put方法将引发Full异常。

    将一个值从队列中取出

    myqueue.get()

    调用队列对象的get()方法从队头删除并返回一个项目。可选参数为block,默认为1。如果队列为空且block1get()就使调用线程暂停,直至有项目可用。如果block为0,队列将引发Empty异常。

    我们用一个例子来展示如何使用Queue

# -*- mode: python; coding: utf-8 -*-import threading import timeimport Queuequeue = Queue.Queue(maxsize=10)class Producer(threading.Thread):    def run(self):        global queue        count = 0        while True:            for i in range(20):                count += 1                msg = "产品" + str(count) + "\n"                queue.put(msg)                print(msg)                time.sleep(0.5)class Consumer(threading.Thread):    def __init__(self, index):        super(Consumer,self).__init__()        self.index = index    def run(self):        global queue        while True:            for i in range(10):                msg = str(self.index) + " 消费了 " + queue.get()                print(msg)                time.sleep(1)        p = Producer()c1 = Consumer(1)c2 = Consumer(2)        p.start()time.sleep(10)c1.start()c2.start()p.join()        








0 0