#!usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = "Samson"
import threading,time
def run(n):
print("task", n)
time.sleep(2)
print("current thread:",threading.current_thread())#当前线程
t_obj = []#存线程实例
start_time = time.time()
for i in range(50):
t = threading.Thread(target=run,args=("t%s" %i,))
#t.setDaemon(True)#把当前线程设置为守护线程,必须在t.start()之前设置,作用为主线程将不会等待该子线程结束
t.start()
t_obj.append(t)
print("total thread:",threading.active_count())#总线程数
for t in t_obj:
t.join()#等待线程执行完
print("%s" %(abs(start_time-time.time())))
线程锁
#!usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = "Samson"
import threading,time
def run(n):
lock.acquire()#锁上
global num
num += 1
#time.sleep(1)#会变为单线程
lock.release()#解锁
lock = threading.Lock()#创建锁
num = 0
t_obj = []#存线程实例
for i in range(50):
t = threading.Thread(target=run,args=("t%s" %i,))
t.start()
t_obj.append(t)
for t in t_obj:
t.join()
print("%s" %num)
线程递归锁
#!usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = "Samson"
import threading,time
def run():
lock.acquire()#锁上
res = run1()
res2 = run2()
lock.release()#解锁
def run1():
lock.acquire()#锁上
global num
num += 1
lock.release()#解锁
def run2():
lock.acquire()#锁上
global num
num += 1
lock.release()#解锁
lock = threading.RLock()#创建递归锁
num = 0
for i in range(10):
t = threading.Thread(target=run)
t.start()
print("Now:",threading.active_count())
while threading.active_count() != 1:
print(threading.active_count())
else:
print("%s" %num)
信号量
#!usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = "Samson"
import threading,time
def run(n):
semaphore.acquire()
time.sleep(1)
print("current thread:",n)
semaphore.release()
if __name__ == "__main__":
semaphore = threading.BoundedSemaphore(5)#信号量为5,表示最多允许5个线程同时执行
for i in range(22):
t = threading.Thread(target=run,args=(i,))
t.start()
while threading.active_count() != 1:
pass
else:
print("All threads done1")
线程之Event事件模仿红绿灯
#!usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = "Samson"
import time
import threading
event = threading.Event()
def lighter():
count = 0
event.set()
while True:
if count <20 and count >10:#变成红灯
event.clear()
print(" 33[41;1mred light is on... 33[0m")
elif count >20:#变成绿灯
event.set()
count = 0
else:
print(" 33[42;1mgreen light is on... 33[0m")
time.sleep(1)
count += 1
def car(name):
while True:
if event.is_set():#设置了标志位,代表绿灯
print("[%s] running..."% name)
time.sleep(1)
else:
print("[%s] sees red light,waiting..."% name)
event.wait()
print(" 33[34;1m[%s] green ligth is on,start going... 33[0m")
light = threading.Thread(target=lighter,)
light.start()
car1 = threading.Thread(target=car,args=("car1",))
car1.start()