欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

互斥量mutex的简单使用(实例讲解)

程序员文章站 2024-02-25 18:34:09
几个重要的函数: #include int pthread_mutex_init(pthread_mutex_t *restrict...

几个重要的函数:

#include <pthread.h>

int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutex_t *restrict attr);    //初始化mutex

int pthread_mutex_destroy(pthread_mutex_t *mutex);  //如果mutex是动态分配的,则释放内存前调用此函数。

int pthread_mutex_lock(pthread_mutex_t *mutex);    //加锁

int pthread_mutex_trylock(pthread_mutex_t *mutex);  //若已有其他线程占用锁,则返回ebusy,否则返回0,不阻塞。

int pthread_mutex_unlock(pthread_mutex_t *mutex);   //解锁

例程:

复制代码 代码如下:

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

int a = 100;
int b = 200;

pthread_mutex_t lock;

void * threada()
{
    pthread_mutex_lock(&lock);
    printf("thread a got lock!\n");
    a -= 50;
    sleep(3);        //如果不加锁,threadb输出会是50和200
    b += 50;        //加锁后会sleep 3秒后,并为b加上50 threadb才能打印
    pthread_mutex_unlock(&lock);
    printf("thread a released the lock!\n");
    a -= 50;
}

void * threadc()
{   
    sleep(1);
    while(pthread_mutex_trylock(&lock) == ebusy) //轮询直到获得锁
    {
        printf("thread c is trying to get lock!\n");
        usleep(100000);
    }
    printf("thread c got the lock!\n");
    a = 1000;
    b = 2000;
    pthread_mutex_unlock(&lock);
    printf("thread c released the lock!\n");

}

void * threadb()
{
    sleep(2);                //让threada能先执行
    pthread_mutex_lock(&lock);
    printf("thread b got the lock! a=%d b=%d\n", a, b);
    pthread_mutex_unlock(&lock);
    printf("thread b released the lock!\n", a, b);
}

int main()
{
    pthread_t tida, tidb, tidc;
    pthread_mutex_init(&lock, null);
    pthread_create(&tida, null, threada, null);
    pthread_create(&tidb, null, threadb, null);
    pthread_create(&tidc, null, threadc, null);
    pthread_join(tida, null);
    pthread_join(tidb, null);
    pthread_join(tidc, null);
    return 0;
}