c - pthread mutex 两个线程互换锁定/解锁是有效的方法吗?

标签 c linux pthreads

我读到互斥锁应该由锁定它的同一个线程解锁。让我们考虑以下场景。

我有一个互斥变量说 myMuteT1T2 是两个线程。

  1. T1 锁定 myMute

  2. T2 解锁 myMute

  3. T2 锁定 myMute

  4. T1 解锁 myMute

这种从不同线程有序锁定/解锁的方法是否有效?

最佳答案

不,这是不正确的。来自 pthread_mutex_lock 手册页:

If a thread attempts to unlock a mutex that it has not locked or a mutex which is unlocked, undefined behavior results.

示例正确顺序:

  • T1 锁定 myMutex
  • T2 锁定 myMutex(阻塞等待 T1 解锁互斥锁)
  • T1 解锁 myMutex(T2 现在锁定互斥锁)
  • T2 解锁 myMutex

编辑:

使用 pthread_cond_wait() 的小示例,为简洁起见省略了错误检查:

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

volatile int value = 0;
pthread_mutex_t mymutex;
pthread_t thread_one;
pthread_t thread_two;
pthread_cond_t cond;

void* main_one(void* ignored)
{
    while (value < 10)
    {
        pthread_mutex_lock(&mymutex);
        pthread_cond_wait(&cond, &mymutex);
        fprintf(stderr, "T1: value=%d\n", value);
        pthread_mutex_unlock(&mymutex);
    }
    return (void*)0;
}

void* main_two(void* ignored)
{
    int i;

    for (i = 0; i < 10; i++)
    {
        pthread_mutex_lock(&mymutex);
        value++;
        fprintf(stderr, "T2: value=%d\n", value);
        pthread_cond_broadcast(&cond);
        fprintf(stderr, "Broadcasted but T1 cannot continue for 1 second\n");
        sleep(1);
        pthread_mutex_unlock(&mymutex);
        pthread_yield();
    }

    return (void*)0;
}

void start_thread(void* (*a_entry_point)(void*),
                  pthread_t* a_handle)
{
    pthread_attr_t thread_attributes;

    pthread_attr_init(&thread_attributes);
    pthread_attr_setdetachstate(&thread_attributes, PTHREAD_CREATE_JOINABLE);
    pthread_create(a_handle, &thread_attributes, a_entry_point, 0);
}

int main()
{
    pthread_mutexattr_t attr;
    pthread_t thread_one_handle;
    pthread_t thread_two_handle;

    /* Init mutex. */
    pthread_mutexattr_init(&attr);
    pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK);
    pthread_mutex_init(&mymutex, &attr);

    /* Init condition. */
    pthread_cond_init(&cond, 0);

    /* Start threads. */
    start_thread(main_one, &thread_one_handle);
    start_thread(main_two, &thread_two_handle);

    /* Wait for threads. */
    pthread_join(thread_one_handle, 0);
    pthread_join(thread_two_handle, 0);

    /* Clean up. */
    pthread_cond_destroy(&cond);
    pthread_mutex_destroy(&mymutex);

    return 0;
}

使用 gcc -Wall -Werror -D_GNU_SOURCE main.c -o main -pthread 编译。

关于c - pthread mutex 两个线程互换锁定/解锁是有效的方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8832577/

相关文章:

linux - gnome登录后播放视频文件

c - 如何在另一个线程完成工作之前挂起一个线程

c - PThread基本程序,好奇这段代码有什么问题

c - 为什么 printf() 格式不适用于全 0 的十进制数?

c - 逐行读取文件,分析字符 --- C

c - 用 C 编写的嵌入式 ARM/Raspberry Pi 汇编

node.js - 需要有关 Nodejs api 的 nginx 配置的帮助

linux - 是否可以在 Linux 上更改命名管道的大小?

c - C中的生产者/消费者,带有pthread信号量和多线程

c - 在 C 语言中创建测量两点之间距离的程序时遇到问题