Linux 同步机制:互斥量

互斥量与信号量对比

互斥量也叫互斥锁,也是Linux的一种同步机制。互斥量相比信号量增加了所有权的概念,被锁的互斥量只能由给它上锁的线程解开,而信号量则无此限制。信号量侧重在资源的数量,可用来实现按一定逻辑调度线程。互斥量则就是纯粹的保护共享资源,不被并发访问,用起来也更加的简单。

对于可以用互斥量解决的场景,就不要用信号量。

举例

下面是典型的生产者消费者例子,读写过程做到原子操作。编译的时候需要链接lpthread, gcc main.c -lpthread.

#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>

char buff[100];
pthread_mutex_t mutex;

/* write, 整个写操作需要要做到原子 */
void* thread1_main(void *p)
{
    pthread_mutex_lock(&mutex);
    printf("thread1 --> write: ");
    strcat(buff, "hello, ");
    sleep(1);
    strcat(buff, "world!");
    printf("%s\n", buff);
    pthread_mutex_unlock(&mutex);
}

/* read, 整个读操作需要要做到原子 */
void* thread2_main(void *p)
{
    pthread_mutex_lock(&mutex);
    while (1) {
        if (strlen(buff) > 0) {
            printf("thread2 --> read:  %s\n", buff);
            break;
        }
    }
    pthread_mutex_unlock(&mutex);
}

int main()
{
    pthread_t tid1, tid2;
    void *ret1, *ret2;
    /* 简便起见,没有通过返回值没有判断下面的函数调用是否ok */
    pthread_mutex_init(&mutex, NULL);
    pthread_create(&tid1, NULL, thread1_main, NULL);
    pthread_create(&tid2, NULL, thread2_main, NULL);
    pthread_join(tid1, &ret1);
    pthread_join(tid2, &ret2);
    pthread_mutex_destroy(&mutex);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值