互斥锁、自旋锁、原子操作

简介: 互斥锁、自旋锁、原子操作

1、互斥锁  -- 临界区资源已经被1个线程占用,另一个线程过来访问临界资源的时候,会被CPU切换线程,不让运行后来的这个线程

适用于 锁住的内容多,(例如红黑数的增加节点操作),切换线程的代价小于等待的代价

2、自旋锁 -- 临界区资源已经被1个线程占用,另一个线程过来访问临界资源的时候,相当于是一个while(1),不断的查看这个资源是否可用,如果可用,就进去访问临界资源,如果不可用,则继续循环访问

适用于锁住的内容少,(例如就执行++操作),切换线程的代价大于等待的代价

3、原子操作  -- 执行的操作完全不可分割,要么全部成功,要么全部失败

最好的方式就是适用原子操作。

 

场景:

1、用10个线程分别对 count 加 100000 次,  看看结果是否是 10*100000

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#define PTHREAD_NUM 10
#define INFO  printf
pthread_mutex_t mutex;
pthread_spinlock_t spin;
int inc(int *v,int add)
{
  int old;
    //汇编,做一个原子操作
  __asm__ volatile(
    "lock;xaddl %2, %1;"
    :"=a" (old)
    :"m"(*v),"a"(add)
    :"cc","memory"
  );
  return old;
}
void * thread_callback(void *arg)
{
  int *count = (int *)arg;
  int i = 100000;
while(i--)
  {
  #if 0
//互斥锁
    pthread_mutex_lock(&mutex);
    (*count)++;
    pthread_mutex_unlock(&mutex);
  #elif 0
//自旋锁
    pthread_spin_lock(&spin);
    (*count)++;
    pthread_spin_unlock(&spin);
  #else
//原子操作
    inc(count,1);
  #endif
    usleep(1);
  }
}
int main()
{
  pthread_t thread[PTHREAD_NUM] = {0};
  pthread_mutex_init(&mutex,NULL);
  pthread_spin_init(&spin,0);
  int count  = 0;
  for(int i = 0;i<PTHREAD_NUM;i++){
    pthread_create(&thread[i],NULL,thread_callback,&count);
  }
  for(int i = 0;i<100;i++)
  {
    INFO("count == %d\n",count);
    sleep(1);
  }
  return 0;
}

2、mutex、lock、atomic 性能对比

//并发
//互斥锁mutex
//  如果获取不到资源会让出cpu
//  使用场景
//    共享区域执行的内容较多的情况
//自旋锁spinlock
//  如果获取不到资源,会原地自旋,忙等
//  使用场景
//    共享区域执行的内容较少的情况
//原子操作
//  不可分割
//  使用场景
//    做简单++、--操作
//
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <time.h>
#define MAX_PTHREAD 2
#define LOOP_LEN    1000000000
#define LOOP_ADD    10000
int count = 0;
pthread_mutex_t mutex;
pthread_spinlock_t spin;
typedef void *(*functhread)(void *arg);
void do_add(int num)
{
  int sum = 0;
  for(int i = 0;i<num;i++)
  {
    sum +=i;
  }
}
int atomic_add(int *v,int add)
{
  int old;
  __asm__ volatile(
    "lock;xaddl %2, %1;"
    :"=a" (old)
    :"m"(*v),"a"(add)
    :"cc","memory"
  );
  return old;
}
void * atomicthread(void *arg)
{
  for(int i  = 0;i<LOOP_LEN;i++){
    atomic_add(&count,1);
  }
}
void * spinthread(void *arg)
{
  for(int i  = 0;i<LOOP_LEN;i++){
    pthread_spin_lock(&spin);
    count++;
    //do_add(LOOP_ADD);
    pthread_spin_unlock(&spin);
  }
}
void * mutexthread(void *arg)
{
  for(int i  = 0;i<LOOP_LEN;i++){
    pthread_mutex_lock(&mutex);
    count++;
    //do_add(LOOP_ADD);
    pthread_mutex_unlock(&mutex);
  }
}
int test_lock(functhread thre,void * arg)
{
  clock_t start = clock();
  pthread_t tid[MAX_PTHREAD] = {0};
  for(int i = 0;i<MAX_PTHREAD;i++)
  {
  //创建线程
    int ret = pthread_create(&tid[i],NULL,thre,NULL);
    if(0 != ret)
    {
      printf("pthread create rror\n");
      return -1;
    }
  }
  for(int i = 0;i<MAX_PTHREAD;i++){
//回收线程
    pthread_join(tid[i],NULL);
  }
  clock_t end = clock();
  //printf("start  -- %ld\n",start);
  //printf("end  -- %ld\n",end);
  //printf("CLOCKS_PER_SEC  -- %ld\n",CLOCKS_PER_SEC);
  printf("spec lock is  -- %ld\n",(end - start)/CLOCKS_PER_SEC);
}
int main()
{
  pthread_mutex_init(&mutex,NULL);
  pthread_spin_init(&spin,0);
//测试spin
  count = 0;
  printf("use spin ------ \n");
  test_lock(spinthread,NULL);
  printf("count == %d\n",count);
//测试mutex
  count = 0;
  printf("use mutex ------ \n");
  test_lock(mutexthread,NULL);
  printf("count == %d\n",count);
//测试atomic
  count = 0;
  printf("use automic ------ \n");
  test_lock(atomicthread,NULL);
  printf("count == %d\n",count);
  return 0;
}

结果

相关文章
|
Web App开发 JavaScript Android开发
微信小程序之内嵌网页(webview)
微信小程序提供了新的开放能力!它终于开放了在小程序中内嵌HTML页面的功能!从微信小程序基础库1.6.4开始,我们就可以在小程序内放置一个组件来链接我们的HTML页面了。
3414 0
|
存储 SQL 安全
探索PHP的世界:从基础到高级
在这篇文章中,我们将一起踏上一段奇妙的旅程,探索PHP的世界。我们将从基础知识开始,逐步深入到高级主题。无论你是初学者还是有经验的开发者,这篇文章都将为你提供有价值的信息和见解。让我们一起揭开PHP的神秘面纱,发现它的强大之处!
|
应用服务中间件 数据安全/隐私保护
Tomcat【部署 02】Web端403 Access Denied You are not authorized to view this page解决方法(Tomcat 10.2.12 版本)
Tomcat【部署 02】Web端403 Access Denied You are not authorized to view this page解决方法(Tomcat 10.2.12 版本)
1540 0
|
XML Java 程序员
【框架源码】SpringBoot核心源码解读之自动配置源码分析
【框架源码】SpringBoot核心源码解读之自动配置源码分析
【框架源码】SpringBoot核心源码解读之自动配置源码分析
|
存储 缓存 NoSQL
Redis 数据结构+线程模型+持久化+内存淘汰+分布式
Redis 数据结构+线程模型+持久化+内存淘汰+分布式
684 0
|
SQL Java 关系型数据库
JDBC 事务和批处理 详解(通俗易懂)
JDBC 第四节 事务和批处理详解!
723 0
|
存储 监控 数据可视化
万字长文简单明了的介绍xxl-job以及quartz
本文主要介绍分布式定时任务框架xxl-job,本文首先会对xxl-job做一个基本的介绍,接着将xxl-job与quartz做一个比较,最后就是介绍xxl-job调度的详细过程。
2010 0
万字长文简单明了的介绍xxl-job以及quartz
|
Swift 开发者
Swift - swift3.0中代理方法的使用
Swift - swift3.0中代理方法的使用
228 0
带你读《2022技术人的百宝黑皮书》——CoHOZ: Contrastive Multimodal Prompt Tuning for Hierarchical Open-set Zero-shot Recognition(4)
带你读《2022技术人的百宝黑皮书》——CoHOZ: Contrastive Multimodal Prompt Tuning for Hierarchical Open-set Zero-shot Recognition(4)
158 0