Linux Driver Development (11) Linux kernel semaphores, mutexes, spin locks

Source: Internet
Author: User
Tags mutex semaphore

Reference:

Http://www.360doc.com/content/12/0723/00/9298584_225900606.shtml

Http://www.cnblogs.com/biyeymyhjob/archive/2012/07/21/2602015.html

Http://blog.chinaunix.net/uid-25100840-id-3147086.html

http://blog.csdn.net/u012719256/article/details/52670098

-------------------------------------------------------------------------------------------------

In drivers, when multiple threads access the same resource at the same time (global variables in the driver are a typical shared resource), "race" may be thrown, so we must have concurrency control over the shared resources. The most common way to solve concurrency control in the Linux kernel is to spin locks and semaphores (most of the time as mutexes).
Spin lock and semaphore "similar but not class", similar to the similarity of their function, "Non-class" refers to them in essence and implementation mechanism is completely different, does not belong to a class.

The spin lock does not cause the caller to sleep, and if the spin lock has been held by another execution unit, the caller has been looping to see if the spin lock has released the lock and "spin" is "spinning in place". While the semaphore causes the caller to sleep, it drags the process out of the running queue unless the lock is acquired. This is their "non-class".

However, whether it is a semaphore or a spin lock, there can be at most one hold at any time, that is, at most one execution unit can acquire a lock at any time. This is their "similarity".

In view of the above characteristics of spin lock and Semaphore, in general, the spin lock is suitable for the case of very short hold time, it can be used in any context, the semaphore is suitable for keeping the time longer, it can only be used in the process context. If the protected shared resource is accessed only in the context of the process, the shared resource can be protected with semaphores, and a spin lock is a good choice if the access time to the shared resource is very short. However, a spin lock must be used if the protected shared resource needs to break context access, including the bottom half of the interrupt handling handle and the top half of the soft interrupt.

The API associated with semaphores is mainly:

Define the semaphore

First, the signal volume

Semaphores, also known as semaphores, are used to coordinate data objects between different processes, and the most important application is inter-process communication in shared memory mode. Essentially, a semaphore is a counter that is used to record access to a resource, such as shared memory. In general, in order to get a shared resource, the process needs to do the following:
(1) test the semaphore that controls the resource.
(2) If the value of this semaphore is positive, the resource is allowed to be used. The process will reduce the semaphore by 1.
(3) If the semaphore is 0, the resource is currently unavailable, the process goes to sleep until the semaphore value is greater than 0, the process is awakened, and the step is transferred (1).
(4) When the process no longer uses a semaphore-controlled resource, the semaphore value is added 1. If there is a process waiting for this semaphore at this time, the process is awakened.
The status of the semaphore is maintained by the Linux kernel operating system and not by the user process. We can see the definition of each structure that the kernel uses to maintain semaphore status from the/usr/src/linux/include/linux/sem.h file. A semaphore is a collection of data that a user can use individually for each element of the collection. The first function to invoke is Semget, which is used to obtain a semaphore ID. Linux2.6.26 the volume structure defined below:

struct semaphore sem;

    

Initialize the semaphore

void Sema_init (struct semaphore *sem, int val);


The function initializes the semaphore and sets the semaphore value of the SEM to Val

void Init_mutex (struct semaphore *sem);


The function is used to initialize a mutex, that is, it sets the value of the semaphore SEM to 1, equivalent to Sema_init (struct semaphore *sem, 1);

void init_mutex_locked (struct semaphore *sem);


The function is also used to initialize a mutex, but it sets the value of the semaphore sem to 0, equivalent to Sema_init (struct semaphore *sem, 0);

Get the signal volume

void down (struct semaphore * sem);


This function is used to get the semaphore SEM, it will cause sleep (this sleep and the following said do not know what is different, since can not be awakened in other places, then what is the use of this down? )and therefore cannot be used in the interrupt context;

int down_interruptible (struct semaphore * sem);


This function function is similar to down, except that the down cannot be interrupted by the signal, but the down_interruptible can be interrupted by the signal(this can be interrupted by the signal, a little puzzled, I am now doing the project is to use is interrupted interrupted, I don't know what this place means.)

int Down_trylock (struct semaphore * sem);


The function attempts to obtain the semaphore SEM, if it can be obtained immediately, it obtains the semaphore and returns 0, otherwise, returns a non-0 value. It does not cause the caller to sleep and can be used in the interrupt context.

Release semaphore

void up (struct semaphore * sem);


The function releases the semaphore SEM, which wakes the waiting person.

2. Mutual exclusion Lock2.1 Concepts

mutexes implement a simple form of "mutually exclusive" (Mutual exclusion) synchronization (so called a mutex). mutexes prohibit multiple threads from entering the protected code "critical section" (critical) at the same time. Therefore, at any moment, only one thread is allowed to enter such a code protected area. a mutex is actually a semaphore in the Count=1 case.

1 //structure2 structMutex {3         /*1:unlocked, 0:locked, negative:locked, possible waiters*/4 atomic_t count;5 spinlock_t Wait_lock;6         structList_head wait_list;7 #ifdef config_debug_mutexes8         structThread_info *owner;9         Const Char*name;Ten         void*Magic; One #endif A #ifdef Config_debug_lock_alloc -         structLockdep_map Dep_map; - #endif the};
1 //defining the Mutex lock2Mutex_init (structmutex*Lock)
or directly with the #define DEFINE_MUTEX (LOCK) can be;3 4 //Get5Mutex_lock (structMutex *Lock)6 7 //Release8Mutex_unlock (structMutex *Lock)

struct mutex lock;

Mutex_init (&lock); initialize Mutex

or directly with the #define DEFINE_MUTEX (LOCK) can be;

#define__mutex_initializer (lockname) \{. Count= Atomic_init (1),. Wait_lock=__spin_lock_unlocked (Lockname.wait_lock),. Wait_list=list_head_init (lockname.wait_list) __debug_mutex_initializer (lockname) __dep_map_mutex_initializer (lo Ckname)}#defineDefine_mutex (Mutexname)structMutex Mutexname =__mutex_initializer (mutexname)extern void__mutex_init (structMutex *Lock,Const Char*name,structLock_class_key *key);



Third: The spin lock related APIs mainly include:

Defining Spin Locks

spinlock_t spin;


Initialize spin lock

Spin_lock_init (Lock)


This macro is used for dynamic initialization of spin lock lock

Get spin Lock

Spin_lock (Lock)


The macro is used to obtain a spin lock lock, and if it is able to obtain the lock immediately, it returns immediately, otherwise it will spin out there until the hold of the spin lock is released;

Spin_trylock (Lock)


The macro attempts to obtain a spin lock lock, if the lock can be obtained immediately, it obtains the lock and returns true, otherwise immediately returns false, actually no longer "in situ circles";

Release spin lock

Spin_unlock (Lock)


The macro releases the spin lock lock, which is paired with Spin_trylock or Spin_lock;

In addition, there is a set of spin locks that are used in the Interrupt case API.

Linux Driver Development (11) Linux kernel semaphores, mutexes, spin locks

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.