码迷,mamicode.com
首页 > 编程语言 > 详细

算法学习

时间:2020-05-23 11:26:16      阅读:58      评论:0      收藏:0      [点我收藏+]

标签:thread   global   控制线   获取   art   pytho   imp   学习   start   

1. threading.Semaphore(value=1) 线程信号量,可以用来控制线程线程的阻塞和释放

sm.acquire()  获取一个信号量,信号量-1,不够-1,则线程阻塞

sm.release()  释放一个信号量,信号量+1

示例如下,控制三个线程的执行顺序:

# -*- 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()

  

 

算法学习

标签:thread   global   控制线   获取   art   pytho   imp   学习   start   

原文地址:https://www.cnblogs.com/zipon/p/12941530.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!