算法学习
2021-01-14 12:14
标签:thread global 控制线 获取 art pytho imp 学习 start 1. threading.Semaphore(value=1) 线程信号量,可以用来控制线程线程的阻塞和释放 sm.acquire() 获取一个信号量,信号量-1,不够-1,则线程阻塞 sm.release() 释放一个信号量,信号量+1 示例如下,控制三个线程的执行顺序: 算法学习 标签:thread global 控制线 获取 art pytho imp 学习 start 原文地址:https://www.cnblogs.com/zipon/p/12941530.html# -*- coding: utf-8 -*-
import threading
import time
sm0 = threading.Semaphore()
sm1 = threading.Semaphore(0)
sm2 = threading.Semaphore(0)
a = 0
def print1():
global a
while True:
sm1.acquire()
if a % 2 == 1:
print(a, "----", a, threading.currentThread().name)
a = a + 1
time.sleep(1)
sm0.release()
def print2():
global a
while True:
sm2.acquire()
if a % 2 == 0:
print(a, "----", a, threading.currentThread().name)
a = a + 1
time.sleep(1)
sm0.release()
def print0():
global a
while True:
sm0.acquire()
print(0, "----", a)
time.sleep(1)
if a % 2 == 1:
sm1.release()
else:
sm2.release()
if __name__ == ‘__main__‘:
t1 = threading.Thread(target=print1)
t0 = threading.Thread(target=print0)
t2 = threading.Thread(target=print2)
t0.start()
t1.start()
t2.start()