zoukankan      html  css  js  c++  java
  • 算法学习

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

      

  • 相关阅读:
    go学习中的零散笔记
    git reset --hard与git reset --soft的区别
    php必学必会
    gdb 解core
    php学习
    高仿京东到家APP引导页炫酷动画效果
    RxHttp
    SVN回滚文件
    遍历枚举
    python3 多线程
  • 原文地址:https://www.cnblogs.com/zipon/p/12941530.html
Copyright © 2011-2022 走看看