27 python 初学(信号量、条件变量、同步条件、队列)

参考博客: www.cnblogs.com/yuanchenqi/articles/5733873.html 

semaphore 信号量:

condition 条件变量:

event 同步条件:条件同步和条件变量同步差不多意思,只是少了锁功能。因为条件同步设计于别访问共享资源的条件环境

 

多线程利器(queue):队列本身有一把锁

q.put(‘xiaoming’, 0)

q.get(0)

q.qsize()  返回队列大小

q.empty()

q.full()

semaphore:

# _author: lily
# _date: 2019/1/29

import threading , time

class MyThread(threading.Thread):
    def run(self):
        if semaphore.acquire():
            print(self.name)
            time.sleep(3)
            semaphore.release()

if __name__ == '__main__':
    semaphore = threading.BoundedSemaphore(5)
    thread_list = []
    for i in range(100):
        thread_list.append(MyThread())
    for i in thread_list:
        i.start()
View Code

condition:

# _author: lily
# _date: 2019/1/29

import threading,time
from random import randint

class Producer(threading.Thread):
    def run(self):
        global L
        while True:
            val = randint(0, 100)
            print('Producer', self.name, ': Append', str(val), L)
            if lock_con.acquire():
                L.append(val)
                lock_con.notify()
                lock_con.release()
            time.sleep(3)

class Consumer(threading.Thread):
    def run(self):
        global L
        while True:
            lock_con.acquire()
            if len(L) == 0:
                lock_con.wait()
                print('Consumer', self.name, ': Delete', str(L[0]), L)
                del L[0]
                lock_con.release()
                time.sleep(0.25)


if __name__ == '__main__':
    L = []
    lock_con = threading.Condition()
    threads = []
    for i in range(5):
        threads.append(Producer())
    threads.append(Consumer())
    for t in threads:
        t.start()
    for t in threads:
        t.join()
View Code

queue:

# _author: lily
# _date: 2019/1/30

import queue

# q = queue.Queue()

q = queue.Queue(3)  # 设置队列大小
q.put('xiaoming', 0)
q.put('xiaohong')
q.put('xiaofang', 0)   # 队列大小为 2 ,当要放置第三个数据的时候,1会被阻塞,0会报错。默认参数为1

print(q.get())
print(q.get())
print(q.get())
print(q.get(0))   # 参数为 0 的时候如果队列空了,还去取值,就会报错。参数为 1 会被阻塞
View Code

 

posted on 2019-01-30 01:29  mlllily  阅读(141)  评论(0编辑  收藏  举报