import threading, time
def run(n):
semaphore.acquire()
time.sleep(1)
print("run the thread: %s" % n)
semaphore.release()
# 如果再次释放信号量,信号量加一,这是超过限定的信号量数目,这时会报错ValueError: Semaphore released too many times
#semaphore.release()
if __name__ == '__main__':
num = 0
semaphore = threading.BoundedSemaphore(2) # 最多允许2个线程同时运行
for i in range(20):
t = threading.Thread(target=run, args=(i,))
t.start()
while threading.active_count() != 1:
pass # print threading.active_count()
else:
print('----all threads done---')
print(num)
import threading, time
import random
def light():
if not event.isSet(): #初始化evet的flag为真
event.set() #wait就不阻塞 #绿灯状态
count = 0
while True:
if count < 10:
print('\033[42;1m---green light on---\033[0m')
elif count < 13:
print('\033[43;1m---yellow light on---\033[0m')
elif count < 20:
if event.isSet():
event.clear()
print('\033[41;1m---red light on---\033[0m')
else:
count = 0
event.set() #打开绿灯
time.sleep(1)
count += 1
def car(n):
while 1:
time.sleep(random.randrange(3, 10))
#print(event.isSet())
if event.isSet():
print("car [%s] is running..." % n)
else:
print('car [%s] is waiting for the red light...' % n)
event.wait() #红灯状态下调用wait方法阻塞,汽车等待状态
if __name__ == '__main__':
car_list = ['BMW', 'AUDI', 'SANTANA']
event = threading.Event()
Light = threading.Thread(target=light)
Light.start()
for i in car_list:
t = threading.Thread(target=car, args=(i,))
t.start()
6. threading.active_count()
返回当前存活的线程对象的数量;通过计算len(threading.enumerate())长度而来
The returned count is equal to the length of the list returned by enumerate().
import threading, time
def run():
thread = threading.current_thread()
print('%s is running...'% thread.getName()) #返回线程名称
time.sleep(10) #休眠10S方便统计存活线程数量
if __name__ == '__main__':
#print('The current number of threads is: %s' % threading.active_count())
for i in range(10):
print('The current number of threads is: %s' % threading.active_count()) #返回当前存活线程数量
thread_alive = threading.Thread(target=run, name='Thread-***%s***' % i)
thread_alive.start()
thread_alive.join()
print('\n%s thread is done...'% threading.current_thread().getName())
7. threading.current_thread()
Return the current Thread object, corresponding to the caller’s thread of control.
返回当前线程对象
>>> threading.current_thread
<function current_thread at 0x00000000029F6C80>
>>> threading.current_thread()
<_MainThread(MainThread, started 4912)>
>>> type(threading.current_thread())
<class 'threading._MainThread'>
import threading, time
def run(n):
thread = threading.current_thread()
thread.setName('Thread-***%s***' % n) #自定义线程名称
print('-'*30)
print("Pid is :%s" % thread.ident) # 返回线程pid
#print('ThreadName is :%s' % thread.name) # 返回线程名称
print('ThreadName is :%s'% thread.getName()) #返回线程名称
time.sleep(2)
if __name__ == '__main__':
#print('The current number of threads is: %s' % threading.active_count())
for i in range(3):
#print('The current number of threads is: %s' % threading.active_count()) #返回当前存活线程数量
thread_alive = threading.Thread(target=run, args=(i,))
thread_alive.start()
thread_alive.join()
print('\n%s thread is done...'% threading.current_thread().getName())
执行结果:
Pid is :11792
ThreadName is :Thread-***0***
------------------------------
Pid is :12124
ThreadName is :Thread-***1***
------------------------------
Pid is :11060
ThreadName is :Thread-***2***
MainThread thread is done...
8. threading.enumerate()
Return a list of all Thread objects currently alive
返回当前存在的所有线程对象的列表
import threading, time
def run(n):
thread = threading.current_thread()
thread.setName('Thread-***%s***' % n)
print('-'*30)
print("Pid is :%s" % thread.ident) # 返回线程pid
#print('ThreadName is :%s' % thread.name) # 返回线程名称
print('ThreadName is :%s'% threading.enumerate()) #返回所有线程对象列表
time.sleep(2)
if __name__ == '__main__':
#print('The current number of threads is: %s' % threading.active_count())
threading.main_thread().setName('Chengd---python')
for i in range(3):
#print('The current number of threads is: %s' % threading.active_count()) #返回当前存活线程数量
thread_alive = threading.Thread(target=run, args=(i,))
thread_alive.start()
thread_alive.join()
print('\n%s thread is done...'% threading.current_thread().getName())
执行结果:
Pid is :12096
ThreadName is :[<_MainThread(Chengd---python, started 12228)>, <Thread(Thread-***0***, started 12096)>, <Thread(Thread-2, initial)>]
------------------------------
Pid is :10328
ThreadName is :[<_MainThread(Chengd---python, started 12228)>, <Thread(Thread-***0***, started 12096)>, <Thread(Thread-***1***, started 10328)>, <Thread(Thread-3, initial)>]
------------------------------
Pid is :6032
ThreadName is :[<_MainThread(Chengd---python, started 12228)>, <Thread(Thread-***0***, started 12096)>, <Thread(Thread-***1***, started 10328)>, <Thread(Thread-***2***, started 6032)>]
Chengd---python thread is done...
9.threading.get_ident()
返回线程pid
import threading, time
def run(n):
print('-'*30)
print("Pid is :%s" % threading.get_ident()) # 返回线程pid
if __name__ == '__main__':
threading.main_thread().setName('Chengd---python') #自定义线程名
for i in range(3):
thread_alive = threading.Thread(target=run, args=(i,))
thread_alive.start()
thread_alive.join()
print('\n%s thread is done...'% threading.current_thread().getName()) #获取线程名
import threading, time
def run(n):
print('-'*30)
print("Now Pid is :%s" % threading.current_thread().ident) # 返回当前线程pid
print("Main Pid is :%s" % threading.main_thread().ident) # 返回主线程pid
print('Now thread is %s...' % threading.current_thread().getName()) # 获取当前线程名
print('Main thread is %s...' % threading.main_thread().getName()) # 获取主线程线程名
if __name__ == '__main__':
threading.main_thread().setName('Chengd---python') #自定义线程名
for i in range(3):
thread_alive = threading.Thread(target=run, args=(i,))
thread_alive.start()
time.sleep(2)
thread_alive.join()
执行结果:
------------------------------
Now Pid is :8984
Main Pid is :3992
Now thread is Thread-1...
Main thread is Chengd---python...
------------------------------
Now Pid is :4828
Main Pid is :3992
Now thread is Thread-2...
Main thread is Chengd---python...
------------------------------
Now Pid is :12080
Main Pid is :3992
Now thread is Thread-3...
Main thread is Chengd---python...