一、互斥锁的基本概念

	进程中的线程在使用某一临界资源时,为了保证临界资源在某一时刻只能被一个任务使用,约定:在使用临界资源之前,都要对临界资源上锁(上锁过程会被堵塞),然后再使用这个资源,用完之后解锁。

二、互斥锁相关API

1、互斥锁初始化
int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutex‐attr_t *mutexattr);
mutex:互斥锁变量的地址
mutexarr:互斥锁属性变量的地址 NULL
代码段:

  pthread_mutex_t mut;
    int pthread_mutex_init_ret = pthread_mutex_init(&mut, NULL);
    if (pthread_mutex_init_ret != 0)
    {
        perror("pthread_mutex_init");
        exit(-1);
    }

2、互斥锁上锁、解锁与销毁
int pthread_mutex_lock(pthread_mutex_t *mutex);
int pthread_mutex_unlock(pthread_mutex_t *mutex);
int pthread_mutex_destroy(pthread_mutex_t *mutex);
返回值:成功返回0,失败返回非0

代码段:

#include <stdio.h>
#include <errno.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>

int data = 0;
void *Pthread_Task(void *arg)
{
   
    pthread_mutex_t *mut = (pthread_mutex_t *)arg;
    for (int i = 0; i < 10; i++)
    {
        //先上锁
        int pthread_mutex_lock_ret = pthread_mutex_lock(&mut);
        if (pthread_mutex_lock_ret != 0)
        {
            perror("pthread_mutex_lock");
            exit(-1);
        }
        //输出
        printf("%d\n", data++);
    
        
        //再解锁
        int pthread_mutex_unlock_ret = pthread_mutex_unlock(&mut);
        if (pthread_mutex_unlock_ret != 0)
        {
            perror("pthread_mutex_unlock");
            exit(-1);
        }
    }
}
int main()
{
    //1初始化互斥锁
    pthread_mutex_t mut;
    int pthread_mutex_init_ret = pthread_mutex_init(&mut, NULL);
    if (pthread_mutex_init_ret != 0)
    {
        perror("pthread_mutex_init");
        exit(-1);
    }
    //2静态初始化互斥锁
    //pthread_mutex_t fastmutex = PTHREAD_MUTEX_INITIALIZER;
    //创建线程
    pthread_t pid1, pid2;
    int pthread_create_ret1 = pthread_create(&pid1, NULL, Pthread_Task, (void *)&mut);
    int pthread_create_ret2 = pthread_create(&pid2, NULL, Pthread_Task, (void *)&mut);
    if (pthread_create_ret1 != 0 || pthread_create_ret2 != 0)
    {
        perror("pthread_create");
        exit(-1);
    }
    pause();
    return 0;
}
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐