• Python锁


     1 #A reentrant lock must be released by the thread that #acquired it. Once a thread has acquired a reentrant lock, the #same thread may acquire it again without blocking; the #thread must release it once for each time it has acquired it.
     2 #递归锁-->为了嵌套锁而设计的
     3 #计数器Counter、字典dict的key存储线程名字,value存储锁标识
     4 #owner = _active[owner].name
     5 #acquire: me = get_ident()  if self._owner == me: 
     6 #                                             self.count+=1
     7 #release:if self._owner != get_ident(): raise
     8 #                else: self._count -= 1
     9 #get_ident():
    10 #Return a non-zero integer that uniquely identifies the #current thread amongst other threads that exist #simultaneously. This may be used to identify per-thread #resources. Even though on some platforms threads #identities may appear to be allocated consecutive #numbers starting at 1, this behavior should not be relied #upon, and the number should be seen purely as a magic #cookie.
    11 #A thread's identity may be reused for another thread #after it exits.
    1 #Condition
    2 #Class that implements a condition variable. A condition #variable allows one or more threads to wait until they are
    3 #notified by another thread. If the lock argument is given 
    4 #and not None, it must be a Lock or RLock object, and it is #used as the underlying lock. Otherwise, a new RLock object #is created and used as the underlying lock.
    5 
    6 #wait(self, timeout=None)
    7 #wait_for(self, predicate, timeout=None) wait无参数,wait_for的参数是一个布尔表达式
    8 #notify(self)
    9 #notify_all(self)
     1 import threading, time
     2 from random import randint
     3 class Producer(threading.Thread):
     4     def run(self):
     5         global L
     6         while True:
     7             val = randint(0, 100)
     8             print('生产者', self.name,':Append'+str(val))
     9             if lock_con.acquire():
    10                 L.append(val)
    11                 print(L)
    12                 lock_con.notify()
    13                 lock_con.release()
    14 class Consumer(threading.Thread):
    15     def run(self):
    16         global L
    17         while True:
    18             lock_con.acquire()
    19             if len(L) == 0:
    20                 lock_con.wait()
    21             print('消费者', self.name,  ":Delete" + str(L[0]), L)
    22             del L[0]
    23             lock_con.release()
    24 if __name__ == '__main__':
    25     L = []
    26     lock_con = threading.Condition()
    27     threads = []
    28     for i in range(5):
    29         threads.append(Producer())
    30     threads.append(Consumer())
    31     for t in threads:
    32         t.start()
    33     for t in threads:
    34         t.join()
    关于start与run
    #start
    #Start the thread's activity.
    #It must be called at most once per thread object.
    #It arranges for the object's run() method to be invoked in a #separate thread of control.
    #This method will raise a RuntimeError if called more than #once on the same thread object.
    #开启一个新的线程来运行run方法,若被多次调用报错
    #run
    #Method representing the thread's activity.
    #You may override this method in a subclass. 
    #The standard run() method invokes the callable object #passed to the object's constructor as the target 
    #argument, if any, with sequential and keyword arguments #taken from the args and kwargs arguments, respectively.

    Python中多线程的两种方式:

    继承Thread类,重写run方法

    直接调用Thread,传入函数名和参数

    Java中多线程的两种方式:

    继承Thread类,覆盖run方法

    实现Runnable接口,覆盖run方法

    用start()来启动线程,实现了真正意义上的启动线程,此时会出现异步执行的效果,结果的随机性。‘ 
    而如果使用run()来启动线程,就不是异步执行了,而是同步执行,不会达到使用线程的意义。是用main这个主线程去调用不同的run方法。

    Semaphore  本质上是 若干个Condition Lock  Counter:释放锁的次数-获取锁的次数+初始值
    This class implements semaphore objects. Semaphores 
    manage a counter representing the number of release() calls 
    minus the number of acquire() calls, plus an initial value. The 
    acquire() method blocks if necessary until it can return 
    without making the counter negative. If not given, value 
    defaults to 1.
    BoundedSemaphore(Semphore) 本质上就是信号量+counter(上界)
    A bounded semaphore checks to make sure its current value
    doesn't exceed its initial value. If it does, ValueError is raised.
    In most situations semaphores are used to guard resources 
    with limited capacity.
    Event: flag  condition(Lock)
    Class implementing event objects.
    Events manage a flag that can be set to true with the set() method and reset to false with the clear() method. 
    The wait() method blocks until the flag is true.  
    The flag is initially false.
    isSet():返回一个布尔值
    set():设置为True  实现的是notify_all()
    clear():设置为False
    wait()
    Lock锁的底层实现:
    1.test-and-set
        value = 0
        while (test-and-set(value)):
            ;//spin 忙等
        如果value=0 跳出while循环,否则自旋
        release时,将value设置为0
    
        无忙等
        class Lock{
            value = 0;
            WaitQueue q;
        }
        Lock Acquire(){
            while(test-and-set(value)){
                add this TCB to wait queue q;
                schedule();
            }
        }
        Lock Release(){
            value = 0
            remove one thread t from q;
            wakeup(t)
        }
    2.exchange
        int lock = 0
        int key = 0
        do{
            key = 1
            while key == 1  exchange(lock, key);
                critical section
            lock = 0
                remainder section
        }
  • 相关阅读:
    pip 最新版 发布(Python包安装和管理工具)
    Python使用cookie 免密登录了解一下
    夯实根基,必知必会的 Python 基础知识
    10个关于文件操作的小功能,都很实用~
    总结一些网站加密和混淆技术
    接口加密如何测试?
    艰难的这年,程序员的未来在哪里?
    警惕“职场PUA”!
    Python面试题及答案汇总
    Python实例练手项目汇总(附源码)
  • 原文地址:https://www.cnblogs.com/liushoudong/p/12633143.html
Copyright © 2020-2023  润新知