Thread and process--line Cheng lock

Source: Internet
Author: User
Tags mutex semaphore

Why do we have three locks?

When we learn three locks, we need to know why we have three locks.
When global resources (counter) are preempted, the problem arises because there is no control over the access of multiple threads to the same resource, causing damage to the data and making the results of the thread run unpredictable. This behavior is called "Thread insecurity." In the development process we have to avoid this situation, how to avoid it? This uses the mutex we mentioned in the review.

Synchronous Lock (Lock) aka Mutex

The concept of Mutex lock

In Python programming, the concept of object mutexes is introduced to ensure the integrity of shared data operations. Each object corresponds to a tag that can be called a "mutex", which is used to guarantee that only one thread can access the object at any one time. In Python we use the lock class provided by the threading module.

We have to rectify the above program, for which we need to add a mutex variable mutex = threading. Lock (), and then we will preempt this lock mutex.acquire () before we scramble for resources, and we release this lock Mutex.release () after the use of the resource is complete. The code is as follows:

Import Threading Import Time counter=0Mutex = Threading. Lock () #创建进程所classMyThread (Threading. Thread): def __init__ (self): threading. Thread.__init__ (self) def run (self):Globalcounter, Mutex Time.sleep (1); if Mutex.acquire (): #判断是否存在进程锁counter+=1Print"I am%s, set counter:%s"%(Self.name, counter) mutex.release () release process   if__name__ = ="__main__":       forIinchRange0, -): My_thread=MyThread () My_thread.start ( )

Recursive lock (Rlock)

In the threading module, two types of locks are defined: threading. Lock and Threading.rlock. There is a slight difference between them, by comparing the following two sections of code to illustrate:

Import Threading   Lock = Threading. Lock () #Lock对象   lock.acquire  ()lock. Acquire ()  #产生了死琐.   Lock . Release ()   Lock . Release ()  print Result: Can not be run down
Import threading = Threading. Rlock () #RLock对象 rlock.acquire () rlock.acquire () #在同一线程内, the program does not clog. rlock.release () rlock.release ( )

The main difference between these two types of locks is that Rlock allows multiple acquire in the same thread. But lock does not allow this situation. Note: If you use Rlock, then acquire and release must appear in pairs, that is, call n times acquire, must call N times release to really release the occupied locks. Threading. Condition
Condiftion can be understood as a high-level lock, which provides more advanced functionality than locks, Rlock allows us to control complex thread synchronization issues. Threadiong. Condition maintains a trivial object internally (by default, Rlock), which can be passed in as a parameter when creating a Condigtion object. Condition also provides acquire, release method, its meaning and the acquire, release method consistent, in fact, it is simply a simple call inside the corresponding method of the object. Condition also provides the following methods (especially note: These methods can only be called after the acquire), otherwise the runtimeerror exception will be reported. ):

############### #这个方法作为补充 ######################

Condition.wait ([timeout]):
The Wait method releases the internal footprint, and the thread is suspended until the notification is woken up or timed out (if the timeout parameter is provided). The program will continue to execute when the thread is awakened and re-occupied.
Condition.notify ():
Wakes up a suspended thread (if there is a pending thread). Note: the Notify () method does not release the occupied locks.
Condition.notify_all ()
Condition.notifyall ()
Wakes all pending threads (if there are pending threads). Note: These methods do not release the locks that are occupied.

Semaphore (semaphore)

Semaphore manages a built-in counter,
Built-in counter whenever acquire () is called-1;
Built-in counter +1 when call Release ();
The counter cannot be less than 0, and when the counter is 0 o'clock, acquire () blocks the thread until another thread calls release ().

#! /usr/bin/env python
#-*-Coding:utf-8-*-
# __author__ = "Wyd"
# DATE:2017/7/18

Import threading
Import time

semaphore= Threading. Semaphore (5) #这里我们只允许同时运行5个线程

def fun ():

If Semaphore.acquire (): #这里我们占用调用一把锁原来的可使用锁数-1
Print (Threading.currentthread (). GetName () + ' get semaphore ') #threading. CurrentThread (). GetName () View the thread print results used
Time.sleep (0.5)
Semaphore.release ()

For I in range: #这里我们开启20个线程
T1=threading. Thread (Target=fun)
T1.start ()

======================================= Results of printing =============

Thread-1get Semaphore
Thread-2get Semaphore
Thread-3get Semaphore
Thread-4get Semaphore
Thread-5get Semaphore

Thread and process--line Cheng lock

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.