Binary

to be foolish,to be hungry

有的事拼命的想要忘记,到最后真的就忘了


Download the theme

Python多线程 N部曲(2)

第二曲

一个小栗子

# 多线程实现红绿灯
# 红灯绿灯亮5秒
import threading,time

event_flag = threading.Event()  # 创建一个 Event() 对象
def lighter_status():
    time_point = 0              # 记录时间
    while True:
        if time_point < 5:
            event_flag.clear()  # 清空 flag,代表红灯
            print("\033[1;41m red light on... \033[0m")
            time.sleep(1)
        elif time_point >=5 and time_point < 10:
            event_flag.set()    # 创建 flag,代表绿灯
            print("\033[1;42m green light on... \033[0m")
            time.sleep(1)
        else:
            time_point = 0
        time_point += 1

def car_status(car_name):
    while True:
        if event_flag.is_set():
            print("[%s] is running ..." % car_name)
            time.sleep(1)
        else:
            print("[%s] is waiting the red light ..." % car_name)
            event_flag.wait()       # 等待flag被设置

light_thread = threading.Thread(target=lighter_status)
baoma = threading.Thread(target=car_status,args=('baoma',))
tesla = threading.Thread(target=car_status,args=('tesla',))
light_thread.start()                # 启动 红绿灯xianc

baoma.start()                       # 启动 车线程
tesla.start()                       # 启动 车线程

PSEvent 类是对一个叫做 flag 标志位的封装,它的方法都是对flag 的操作,这个flag 相当于一个全局变 量,可以被所有的线程访问

set() 设置 flag,相当于初始化一个flag

is_set() 判断 flag 是否被设置

clear() 清除 flag

wait() 如果flag 没有被设置就让线程等到flag 被设置再向下执行

Queue

import queue
# 普通队列 先进先出
q = queue.Queue(maxsize = 10)
for i in range(10):
    q.put(i)              # put 向队列里放对象
print(q.get())
print(q.get())            # get 取出一个对象
print(q.get())

# 后进先出队列 相当于栈 
q = queue.LifoQueue(maxsize = 10)
for i in range(10):
    q.put(i)
print(q.get())
print(q.get())

# 优先级队列,传入的对象按优先级排序,数字越小优先级越高
q = queue.PriorityQueue(maxsize = 10)
q.put((10,'bob'))
q.put((2,'alice'))
q.put((1,'Binary'))
print(q.get())
print(q.get())

又一个小栗子

# 生产者消费者
import queue,threading,time

q = queue.Queue(maxsize=5)   

def productor(name):
    while True:
        if q.empty():
            print("\033[1;41m [%s]开始生产...\033[0m" % name)
            for i in range(5):
                q.put('product'+str(i))
                print('[%s] 生产了产品[%s]' % (name,i))
                time.sleep(2)
        else:
            print("\033[1;42m 还有产品剩余...不生产... \033[0m")
            time.sleep(1)

def consumer(name):
    while True:
        print("[%s] 消费了 [%s]" % (name,q.get()))
        time.sleep(3)
        
p1 = threading.Thread(target=productor,args=('Binary',))
c1 = threading.Thread(target=consumer,args=('Joker',))
c2 = threading.Thread(target=consumer,args=('new_one',))

p1.start()
c1.start()
c2.start()
最近的文章

Python多线程 N部曲(3)

第三曲多进程库名multiprocessing简单例子# 使用方法和多线程类似from multiprocessing import Processimport osimport timedef P_func(name): print(name,os.getpid()) # 打印进程的 ID time.sleep(2)p_list = []if __name__ == '__main__': for i in range(10): p = Proces...…

继续阅读
更早的文章

Nc

nc基本通讯server: nc -lp port 监听port ,等待连接client : nc -nv ip port 连接服务器端文件传递server : nc -lp port < file -q 1 把文件放到port 等待连接的客户端下载client : nc -nv ip port > file 连接服务器下载文件或者server : nc -lp port > file 等待连接的客户端上传文件client : nc -nv ...…

继续阅读