美文网首页
互斥锁 Mutex

互斥锁 Mutex

作者: 写一行代码 | 来源:发表于2020-08-24 19:56 被阅读0次

安装帮助手册:sudo apt-get install manpages-posix-dev
头文件:#include <pthread.h>

pthread_mutex_init

int pthread_mutex_init(pthread_mutex_t *restrict mutex,
const pthread_mutexattr_t *restrict attr);
功能:
初始化一个互斥锁。
参数:
mutex:互斥锁地址。类型是 pthread_mutex_t 。
attr:设置互斥量的属性,通常可采用默认属性,即可将 attr 设为 NULL。

可以使用宏 PTHREAD_MUTEX_INITIALIZER 静态初始化互斥锁,比如:
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

这种方法等价于使用 NULL 指定的 attr 参数调用 pthread_mutex_init() 来完成动态初始化,不同之处在于 PTHREAD_MUTEX_INITIALIZER 宏不进行错误检查。

返回值:
成功:0,成功申请的锁默认是打开的。
失败:非 0 错误码

pthread_mutex_destroy

int pthread_mutex_destroy(pthread_mutex_t *mutex);
功能:
销毁指定的一个互斥锁。互斥锁在使用完毕后,必须要对互斥锁进行销毁,以释放资源。
参数:
mutex:互斥锁地址。
返回值:
成功:0
失败:非 0 错误码

pthread_mutex_lock

int pthread_mutex_lock(pthread_mutex_t *mutex);
功能:
对互斥锁上锁,若互斥锁已经上锁,则调用者阻塞,直到互斥锁解锁后再上锁。
参数:
mutex:互斥锁地址。
返回值:
成功:0
失败:非 0 错误码

int pthread_mutex_trylock​

int pthread_mutex_trylock(pthread_mutex_t *mutex);
调用该函数时,若互斥锁未加锁,则上锁,返回 0;
若互斥锁已加锁,则函数直接返回失败,即 EBUSY。

pthread_mutex_unlock

int pthread_mutex_unlock(pthread_mutex_t *mutex);
功能:
对指定的互斥锁解锁。
参数:
mutex:互斥锁地址。
返回值:
成功:0
失败:非0错误码

测试程序

pthread_mutex_t mutex; //互斥锁
​
void printer(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)
{
    char *str = "hello";
    printer(str); 
}
​
void *thread_fun_2(void *arg)
{
    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;
}
​

相关文章

  • 自旋锁 和 互斥锁

    自旋锁 和 互斥锁 Pthreads提供了多种锁机制: (1) Mutex(互斥量):pthread_mutex_...

  • 系统编程-------线程编程----线程互斥锁

    线程互斥锁 互斥锁pthread_mutex_t 参数: 返回值: pthread_mutex_inti;初始化互...

  • 进程间同步

    互斥锁 进程间也可以使用互斥锁同步, 但必须在pthread_mutex_init(&mutex, attr)之前...

  • Golang 锁的相关知识

    Golang锁分类:互斥锁(Mutex)、读写锁(RWMutex)。 互斥锁 在编写代码中引入了对象互斥锁的概念,...

  • 线程 -- 互斥锁

    互斥锁的使用步骤: # 创建锁mutex = threading.Lock()# 上锁mutex.acquire(...

  • 第二十六天--[互斥与同步]

    学习内容:互斥与同步收获: 了解了互斥与同步的概念; 了解了互斥锁(mutex)的使用:pthread_mutex...

  • golang rwmutex的实现原理

    1. 前言 前面我们聊了互斥锁Mutex,所谓读写锁RWMutex,完整的表述应该是读写互斥锁,可以说是Mutex...

  • C++锁

    锁的种类 互斥锁、条件锁、自旋锁、读写锁、递归锁。 互斥锁 头文件: 类型:pthread_mutex_t, 函数...

  • Go 语言的锁

    Go 语言提供两类锁: 互斥锁(Mutex)和读写锁(RWMutex)。其中读写锁(RWMutex)是基于互斥锁(...

  • Golang学习笔记-sync

    Mutex sync.Mutex为互斥锁,同一时间只能有一个goroutine获得互斥锁。 使用Lock()加锁,...

网友评论

      本文标题:互斥锁 Mutex

      本文链接:https://www.haomeiwen.com/subject/pxcojktx.html