Synchronization and mutual exclusion mechanism spin lock mutex

A synchronization mechanism for mutual exclusion

应用场景:多线程的时候。当多个执行单元同时被执行,处理的是同一个资源时,就会导致竞态,这个时候就需要用同步或者互斥的方法来解决竞态。

线程和进程的区别:进程是拥有资源的最小单位,线程是参与调度的最小单位。

执行单元:进程、线程、SMP(对称多处理器)
资源:软件资源或者是硬件资源

并发:多个执行单元同时被执行。
竞态:多个执行单元同时被执行,处理的是同一个资源,就会导致竞态。

临界区:对资源进程操作的代码区
临界资源:可能会被多个执行单元同时访问并操作的资源
  • Leads race reasons:

     1.多进程同时访问操作临界资源(进程和抢占它的进程之间会导致竞态)
     2.进程和中断
     3.对称多处理器
    
  • Solution race conditions:

     同步:强调的是顺序性
     互斥:强调的是排他性
    
  • Specific solutions:

     1.屏蔽中断
     2.自旋锁
     3.原子操作
     4.互斥体(互斥锁)
     5.信号量
    

Second, the spin lock

Header: linux / spinlock.h
spinlock Data Type: spinlock_t

Lock mechanism, complete mutual exclusion, and the like mutex

The spin lock;
critical section;
solution spin lock;

After the spin lock is locked, it will block out the process to seize, the process of scheduling related functions if the process occurs in a critical region (for example: sleep), equivalent to give up the execution of the CPU. At this time, the operating system to schedule other processes (process 2), 2 in the implementation process needs to be locked, but the process has not released the lock 1, 2 process will not obtain a lock, will enter the spin state, resulting in CPU will be 100% occupied. If the CPU is single core, after the sleep function, because the process 1 process 2 (enter the spin state) the CPU resources are occupied, unlock never executed, it will lead to a deadlock.

Note: Especially in the case of single-core CPU, can not appear on the process of scheduling related functions in spin lock to protect critical areas.

  • Related functions:
    to define a flag flag to determine whether to open for the first time
spin_lock_init(spinlock_t *lock)
功能:初始化自旋锁
参数:
    @lock      自旋锁结构体指针   

void spin_lock(spinlock_t *lock)
功能:自旋锁上锁
参数:
    @lock    自旋锁结构体指针 
    
int spin_trylock(spinlock_t *lock)
功能:自旋锁上锁
参数:
    @lock    自旋锁结构体指针 
特点:如果上锁失败,错误返回

void spin_unlock(spinlock_t *lock)
功能:自旋锁解锁
参数:
    @lock    自旋锁结构体指针 

Spinlock initialization:
Here Insert Picture Description
spin lock lock and unlock:
Here Insert Picture Description
flag definitions and subtraction operation functions:
Here Insert Picture Description
operating results:
Here Insert Picture Description

Third, the mutex

Header: <linux / mutex.h>
Data Type: struct mutex

Mutex lock
critical section
mutex unlock

  • related functions:
mutex_init(struct mutex *mutex)
    功能:初始化互斥体
    参数:
        @mutex  互斥体结构体指针
        
void  mutex_lock(struct mutex *lock)		
	功能:互斥体上锁
	参数:
		@lock   互斥体结构体指针  
	特点:互斥体上锁失败,会导致应用层进程休眠
void  mutex_unlock(struct mutex *lock)		
	功能:互斥体解锁
	参数:
		@lock   互斥体结构体指针   

Locking and unlocking the mutex:
Here Insert Picture Description
the results:
Here Insert Picture Description

Published an original article · won praise 1 · views 23

Guess you like

Origin blog.csdn.net/weixin_46097899/article/details/104526364
Recommended