python锁_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 importthreading, time2 from random importrandint3 classProducer(threading.Thread):4 defrun(self):5 globalL6 whileTrue:7 val = randint(0, 100)8 print('生产者', self.name,':Append'+str(val))9 iflock_con.acquire():10 L.append(val)11 print(L)12 lock_con.notify()13 lock_con.release()14 classConsumer(threading.Thread):15 defrun(self):16 globalL17 whileTrue:18 lock_con.acquire()19 if len(L) ==0:20 lock_con.wait()21 print('消费者', self.name, ":Delete" +str(L[0]), L)22 delL[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 inthreads:32 t.start()33 for t inthreads: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:释放锁的次数-获取锁的次数+初始值

Thisclassimplements 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 blocksif necessary until it can returnwithout making the counter negative. Ifnotgiven, value

defaults to1.

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() methodandreset to false with the clear() method.

The wait() method blocks until the flagistrue.

The flagisinitially false.

isSet():返回一个布尔值

set():设置为True 实现的是notify_all()

clear():设置为False

wait()

Lock锁的底层实现:1.test-and-set

value=0while (test-and-set(value)):

;//spin 忙等

如果value=0 跳出while循环,否则自旋

release时,将value设置为0

无忙等classLock{

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 tfromq;

wakeup(t)

}2.exchange

int lock=0

int key=0

do{

key= 1

while key == 1exchange(lock, key);

critical section

lock=0

remainder section

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值