mutex 使用介绍


一、mutex 基本函数

1. int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *mutexattr);

可使用宏静态初始化互斥量,如下:等价于用NULL指定 attr 调用 pthread_mutex_init 函数

pthread_mutex_t  mutex = PTHREAD_MUTEX_INITIALIZER;

2. int pthread_mutex_lock(pthread_mutex_t *mutex);

对互斥量上锁,若已经上锁,则调用者一直阻塞,直到互斥锁解锁后再上锁

3. int pthread_mutex_trylock(pthread_mutex_t *mutex);

非阻塞上锁,如果互斥量处于未锁住状态,那么将锁住互斥量,否则立即返回失败 EBUSY

4. int pthread_mutex_unlock(pthread_mutex_t *mutex);

释放锁

5. int pthread_mutex_destory(pthread_mutex_t *mutex);

用于销毁互斥量,释放所有相关联的资源(由 pthread_mutex_init自动申请的资源)

二、mutex 多线程

1. 多线程没有引入 mutex

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

void printer(const char *str)
{
        while(*str!='\0')
        {
                putchar(*str);
                fflush(stdout);
                str++;
                sleep(1);
        }
        printf("\n");
}

void *thread_fun_1(void *arg)
{
        const char *str = "hello";
        printer(str);
}

void *thread_fun_2(void *arg)
{
        const char *str = "world";
        printer(str);
}

int main(void)
{
        pthread_t tid1, tid2;

        pthread_create(&tid1, NULL, thread_fun_1, NULL);
        pthread_create(&tid2, NULL, thread_fun_2, NULL);
        pthread_join(tid1, NULL);
        pthread_join(tid2, NULL);
        return 0;
}

在这里插入图片描述

2. 多线程引入 mutex

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

pthread_mutex_t mutex;

void printer(const char *str)
{
    pthread_mutex_lock(&mutex);
    while(*str!='\0')
    {
        putchar(*str);
        fflush(stdout);
        str++;
        sleep(1);
    }
    printf("\n");
    pthread_mutex_unlock(&mutex);
}

void *thread_fun_1(void *arg)
{
    const char *str = "hello";
    printer(str);
}

void *thread_fun_2(void *arg)
{
    const char *str = "world";
    printer(str);
}

int main(void)
{
    pthread_t tid1, tid2;

    pthread_mutex_init(&mutex, NULL);
    pthread_create(&tid1, NULL, thread_fun_1, NULL);
    pthread_create(&tid2, NULL, thread_fun_2, NULL);
    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);
    pthread_mutex_destroy(&mutex);
    return 0;
}

在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值