Mutex lock(互斥锁)是在多线程编程中最常用的锁,它的基本原理是sleep waiting,当锁有冲突时,等锁的一方会挂起线程进入睡眠状态,等待信号量来再唤醒挂起的线程。
Spin lock(自旋锁)它的基本原理是busy waiting,当锁有冲突时,不会挂起线程而是通过cup不停的轮询锁状态,一旦有锁从临界区出来它可以马上尝试获取锁。
那在实际使用时该如何选择该用哪种锁呢?小编特意编写了如下代码来验证不同情况下两种锁的不同表现:
/*
* mutex_spin_lock_test.c
*
* Created on: Dec 10, 2022
* Author: Xiong Zhen
*/
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <semaphore.h>
#include <time.h>
#include <assert.h>
#include <unistd.h>
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
typedef int (*lockfun)(volatile void *);
struct arg {
uint64_t total_cost_ns;
uint64_t avg_cost_per_req_ns;
uint64_t total_requests;
uint64_t total_test_time_ns;
uint64_t requests_per_seconds;
double avg_cpu_usage;
volatile void *lock_obj;
lockfun lock;
lockfun unlock;
int repeat_cnt;
bool stop;
};
void *lock_thread(void *p) {
struct arg *arg = p;
struct timespec now;
struct timespec start;
volatile int i;
while (!arg->stop) {
arg->lock(arg->lock_obj);
clock_gettime(CLOCK_MONOTONIC, &start);
for (i = 0; i < arg->repeat_cnt; i++) {}
arg->total_requests++;
clock_gettime(CLOCK_MONOTONIC, &am