zoukankan      html  css  js  c++  java
  • 锁、信号量和资源互斥分别指什么?请用python程序举例说明。

    锁既是给公共资源增加限制。如果是死锁的必须满足以下四个条件,互斥,不可剥夺,请求与保持, 循环等待,只要系统出现死锁,这四个条件必须成立。

    信号量,有时被称为信号灯。是在多线程环境下使用的一种设施,他负责协调各个线程,以保证他们能够正确、合理的使用公共资源。

    互斥:是指某一资源同时只允许一个访问者对其进行访问,具有唯一性和排它性。

    # ### 信号量 Semaphore
    from threading import Semaphore, Thread
    import time
    
    
    def func(i, sem):
        with sem:
            print(i)
            time.sleep(10)
    
    
    sem = Semaphore(6)
    for i in range(20):
        Thread(target=func, args=(i, sem)).start()
    # 枷锁
    import time, threading
    count=0 #声明全局变量
    lock=threading.Lock() #申请一把锁
    def lajifenlei():
        global count #引用全局变量
        lock.acquire()  #加锁
        count+=1
        lock.release() #释放锁
        time.sleep(1)
        print(count)
    
    for i in range(10):
        th = threading.Thread(target=lajifenlei,) #声明线程数
        th.start() #启动线程
    while threading.activeCount()!=1:
        pass
  • 相关阅读:
    pycharm的一些操作指令和技巧
    Python开发:模块
    python字符编码
    Pyhton开发:Python基础杂货铺
    Python之函数
    python介绍
    记录
    HDOJ3699 A hard Aoshu Problem[暴力]
    HDOJ3697 Selecting courses[贪心]
    HDOJ4054 Hexadecimal View[编码题]
  • 原文地址:https://www.cnblogs.com/youhongliang/p/13069267.html
Copyright © 2011-2022 走看看