学堂 学堂 学堂公众号手机端

linux 互斥锁的简单理解

lewis 1年前 (2024-04-27) 阅读数 12 #技术


互斥锁,类似于公共电话那样,安装一个公用电话(初始化锁),A拿起话筒(加锁),开始使用(访问资源),使用结束(释放锁),B再来使用。

初始化锁有两种方式:


1,API函数

pthread_mutex_init()

2,利用宏

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

利用宏,速度快,但是不能进行错误检查,不能进行配置,如果需要配置的话就用API,不需要则用宏。

/***************************************************
##filename : mutex1.c
##author : GYZ

##create time : 2018-10-11 16:02:37
##last modified : 2018-10-11 16:43:54
##description : NA
***************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>

pthread_mutex_t mutex;

void printString(char *str)
{
printf("%s",str);
}
void threadFun1(void *arg)
{
char *str1 = "threadFun1\n";
printString(str1);
}
void threadFun2(void *arg)
{
char *str2 = "threadFun2\n";
printString(str2);
}
int main(int argc,char *argv[])
{
pthread_t tid1,tid2;
/*1,initialize mutex locks*/
pthread_mutex_init(&mutex,NULL);
/*2.1,create thread 1*/
pthread_create(&tid1,NULL,(void *)&threadFun1,NULL);
/*2.2,create thread 2*/
pthread_create(&tid2,NULL,(void *)&threadFun2,NULL);
/*3.1,wait for the thread to end and recycle resources*/
pthread_join(tid1,NULL);
/*3.2,wait for the thread to end and recycle resources*/
pthread_join(tid2,NULL);
/*4,destroy the mutex locks*/
pthread_mutex_destroy(&mutex);
return 0;
}

说明,在不使用该互斥锁的情况下可以使用,直接对互斥锁进行毁坏,使用函数:

int pthread_mutex_destroy(pthread_mutex_t *mutex);

如果还使用该互斥锁,则在上个线程使用完毕之后释放锁,然后让下个线程再去锁,使用函数:

int pthread_mutex_unlock(pthread_mutex_t * mutex);

版权声明

本文仅代表作者观点,不代表博信信息网立场。

热门