python 多线程小方法

import time
from multiprocessing import Process, Lock, JoinableQueue
from multiprocessing import Semaphore, Event
import random
import json


# def get_tic(man, lock):
#     time.sleep(random.random())
#     lock.acquire()
#     with open("ticket", mode="r", encoding="utf-8") as f:
#             tic_info = json.load(f)
#     if tic_info["count"] > 0:
#         print("邮票", man)
#         with open("ticket", mode="w", encoding="utf--8") as f:
#             tic_info["count"] = 0
#             json.dump(tic_info, f)
#             print("已购买!")
#     else:
#         print("票呢")
#     lock.release()
#
#
# if __name__ == '__main__':
#     l = Lock
#     for i in range(10):
#         p = Process(target=get_tic, args=(i, l()))
#         p.start()

# def wash(i, s):
#     s.acquire()
#     print("i %s 烧饼来洗脚,papapa" % i)
#     time.sleep(random.randrange(3, 5))
#     print("i%s,shao饼出来了" % i)
#     s.release()
#
# if __name__ == '__main__':
#     s = Semaphore(5)
#     for i in range(20):
#         p = Process(target=wash, args=(i, s))
#         p.start()

#
# def traffic_lights(e):
#     while 1:
#         print("红灯停停停!")
#         time.sleep(5)
#         e.set()
#         print("绿灯行,走走走走!")
#         time.sleep(3)
#         e.clear()
#
#
# def car(i, e):
#     if not e.is_set():
#         print(i, "等待")
#         e.wait()
#         print("走咯")
#     else:
#         print("出门一路绿灯!")
#
#
# if __name__ == '__main__':
#     e = Event()
#     tl = Process(target=traffic_lights, args=(e, ))
#     tl.start()
#     while 1:
#         time.sleep(3)
#         for i in range(5):
#                 c = Process(target=car, args=(i, e))
#                 c.start()


from multiprocessing import Queue

# q = Queue(5)
# q.put(0)
# q.put(1)
# q.put(2)
# q.put(3)
# q.put(4)
# try:
#     # q.put_nowait()
#     q.
#     q.put(5)
#
# except:
#     print("满了")
# print(q.get())
# print(q.get())
# print(q.get())
# print(q.get())
# print(q.get())
# try:
#     q.put_nowait()
#     print(q.get())
# except:
#     print("None")

#
# def he(q):
#     print(q.get().decode("utf-8"))
#     print(q.get())
#
#
# def her(q):
#     q.put("约?".encode("utf-8"))
#     print(q.get())
#
#
# if __name__ == '__main__':
#     q = Queue(5)
#     h = Process(target=he, args=(q,))
#     she = Process(target=her, args=(q,))
#     h.start()
#     she.start()
#     time.sleep(1)
#     q.put("好好工作")

#
# def producer(q):
#     for i in range(10):
#         time.sleep(1)
#         baozi = "包子 %s 号" % i
#         print(baozi)
#         q.put(baozi)
#     print("今天的任务完成了!")
#     # q.put(None)


# def have(q):
#     while 1:
#         take = q.get()
#         if take:
#             print("吃  %s" % take)
#             time.sleep(0.5)
#         else:
#             print("没得吃了!")
#             break
#
#
# if __name__ == '__main__':
#     q = Queue(11)
#     p = Process(target=producer, args=(q,))
#     h = Process(target=have, args=(q,))
#     p.start()
#     h.start()
#     p.join()
#     q.put(None)

#
# 明天默写内容:
        # 1 同步锁的作用
        # 答:  多个进程某一段相同内容的代码, 只允许最先到达的进程处理,释放之后才允许其他进程继续执行,
        #     优点1: 保护数据安全, 避免不可预见的意外,
        #     优点2: 异步进程在进行其他代码时不必等待, 只在这一段等待, 效率同比当前进程结束在运行其他进程效率要高


# 2 事件中有哪些方法
        # 1. wait()  ,阻塞标记,
        # 2. set(), 阻塞标记处不等待效果设置为True,  在不再等待
        # 3. is_set(),判断阻塞标记wait()的真伪
        # 4, clear(), 还原wait标记 为False状态, 阻塞恢复等待

# 3 队列有哪些方法  注意 #  队列的查询结果会有延迟, 放和取数据需要时间, 查询qsize, empty,full都会有误差
        # get()获取队列中的内容
        # put()向队列中存数据
        # empty() 判断队列是否为空
        # full() 判断队列是否满载
        # put_nowait() 放入数据是不等待, 满载即刻报错
        # get_nowait() 获取数据时不等待, 空载即刻报错
        # a = Queue()
        # # a.get(False)  # 取消阻塞状态, 效果与get_nowait相同
        # a.put(2, False)   #取消阻塞状态, 效果与put_nowait相同
        # # print(a.get())
        # # qsize()  获取队列数据单元的数量
        # a.put(5)
        # print(a.qsize())
        # a.close()   #关闭队列,不允许放, 也不能拿数据
        # print(a.get())
# 4 简述生产者消费者模型
        #  生活中,生产者产生商品, 消费者消费商品, 但是消费者和生产者不直接进行交流, 而是交给中间平台 ,
        #  中间平台作为第三方沟通生产者和消费者, 双方之间无需等待, 互不干涉, 解决双方之间的不同步问题(i/o能力不同)
#
# 作业:
# 1 基于队列写一个有多个消费者和生产者的模型
# JoinableQueue  #  一个具有空载发出信号的队列
# 1 ,可以不断往里面存放 数据,  join()等待队列的数据拿完,执行往下代码
# 2, 取数据的时候用task_done()告诉队列去了数据

#
# class Person(Process):
#     def __init__(self, q):
#         super().__init__()
#         self.q = q
#
#     def run(self):
#         while 1:
#             time.sleep(0.1)
#             product = self.q.get()
#             print(self.name, "买下了", product)
#             self.q.task_done()
#
#
# class Producer(Process):
#     def __init__(self, pai, q):
#         super().__init__()
#         self.pai = pai
#         self.q = q
#
#     def run(self):
#         for i in range(20):
#             self.q.put("product %s " % i)
#             print("%s 生产了商品%s" % (self.pai, i))
#             time.sleep(0.5)
#         print("I'm back home")
#         self.q.join()
#         print("卖完了!")
#
#
# if __name__ == '__main__':
#     q = JoinableQueue(20)
#     pro = Producer("dell", q)
#     pro.start()
#     man = Person(q)
#     man.daemon = True  # man跟随主进程结束
#     man.start()
#     pro.join()  # 等待pro进程结束接续下面的代码
#     # time.sleep(5)
#     print("main process is end !")
# 2再有时间的话:
# 使用同步锁写一个简单的抢票程序,提供并发查票和并发买票的功能

def buy(i, q):
    with open("ticket", mode="r", encoding="utf-8") as f:
        info = json.load(f)
    print(info["count"], i)   # 进入查询
    time.sleep(random.random())  # 模拟网络延迟
    with open("ticket", mode="r", encoding="utf-8") as f:  # 模拟付款
        info2 = json.load(f)
    q.acquire()  # 锁定下段代码
    if info2["count"] > 0:
        print("%s 余票 %s 张" % (i, info["count"]))
        print("我的了%s" % i)
        info2["count"] = 0
        info2["me"] = 1
        info2["owner"] = i
        with open("ticket", mode="w", encoding="utf-8") as f1:
            json.dump(info2, f1)
    q.release()
    with open("ticket%s" % i, mode="w", encoding="utf-8") as f:
        json.dump(info2, f)  # 模拟购买情况
    # time.sleep(5)
    # with open()


if __name__ == '__main__':
    q = Lock()
    lst = []
    for i in range(20):
        b = Process(target=buy, args=(i, q))
        lst.append(b)
        b.start()
    for p in lst:
        p.join()

    print("结束")

 

posted @ 2018-10-24 19:50  python传言  阅读(158)  评论(0编辑  收藏  举报