#!/usr/bin/env python
# -*- coding:utf-8 -*-

import threading
import time
import random

# 1-互斥锁 Lock 同一时刻只能有1个线程运行,需要将锁传给任务函数
number = 0
lock = threading.Lock()

def plus(lk):
global number

#开始加锁
lk.acquire()

for _ in range(1000000):
number += 1
print("子线程%s运算结束后,number = %s" % (threading.current_thread().getName(), number))

# 释放锁,让别的线程也可以访问number
lk.release()


if __name__ == '__main__':
for i in range(2):

# 需要把锁当做参数传递给plus函数
t = threading.Thread(target=plus, args=(lock,))
t.start()

# 等待2秒,确保2个子线程都已经结束运算。
time.sleep(2)

print("主线程执行完毕后,number = ", number)


# 2-信号锁 Semaphore 允许一定数量的线程同时更改数据
def mythread(num,se):
se.acquire()
print("run the thread %s"%num)

time.sleep(1)

se.release()

#允许2个线程同时允许
semaphore=threading.BoundedSemaphore(2)

#启动6个线程
for i in range(6):
t=threading.Thread(target=mythread,args=(i,semaphore))
t.start()


# 3-条件锁 codintion 多个线程运行时,当一个线程执行后,在满足一定条件下,暂停执行当前线程,执行另一线程
num=0
con=threading.Condition()

class mythread(threading.Thread):
def __init__(self,name,action):
super(mythread,self).__init__()
self.name=name
self.action=action

def run(self):
global num
con.acquire()

print("开始执行%s"%self.name)
while True:
if self.action=="add":
num+=1
elif self.action=="reduce":
num-=1
else:
exit(1)
print("当前num为:",num)

time.sleep(1)

if num==5 or num==0:
print("%s暂停执行"%self.name)
con.notify()
con.wait()
print("%s开始执行"%self.name)
con.release()

if __name__=="__main__":
t1=mythread("线程1","add")
t2=mythread("线程2","reduce")
t1.start()
t2.start()

# 4-事件锁 全局定义一个flag 当flag=False,线程调用wait(),被阻塞,不执行,当flag=True,线程不在阻塞
# set()->flag=True clear()->flag=False wait()->等待红绿灯信号 is_set()->是否放行状态
t=threading.Event()

def lighter():
# 绿灯时间
gree_time=5

# 红灯时间
red_time=5

# 初始为红灯
t.set()

while True:
print("\33[32;0m 绿灯亮...\033[0m")
time.sleep(gree_time)
t.clear()

print("\33[32;0m 红灯亮...\033[0m")
time.sleep(red_time)
t.set()

def runcar(name):
while True:
if t.is_set():
print("一辆[%s] 呼啸开过..." % name)
time.sleep(1)
else:
print("一辆[%s]开来,看到红灯,无奈的停下了..." % name)
t.wait()
print("[%s] 看到绿灯亮了,瞬间飞起....." % name)


if __name__=="__main__":
light=threading.Thread(target=lighter,)
light.start()

for name in ['奔驰', '宝马', '奥迪']:
car=threading.Thread(target=runcar,args=(name,))
car.start()


#5-定时器Timer 在指定时间过后执行某个函数
def getNum():
rand=random.random()
print(rand)

t=threading.Timer(4,getNum)
t.start()

posted on 2018-12-09 17:14  新美好时代  阅读(157)  评论(0编辑  收藏  举报