线程可以在接收到条件信号时唤醒但不能同时获得互斥锁

标签 c linux multithreading

<分区>

我编写了一个程序来测试 pthread_cond_signal。首先,一个线程在 pthread_cond_wait 中阻塞,因为条件为假。然后主线程获取互斥量,并尝试唤醒被阻塞的线程。但是程序收到 SIGSEGV。为什么?

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>

typedef struct condTest_s  condTest_t;
struct condTest_s {
    pthread_mutex_t mutex;
    pthread_cond_t cond;
};

condTest_t test; // global variable

/* newly created thread */
void *thread1(void *arg)
{
    printf("thread1 starts \n");
    pthread_mutex_lock(&test.mutex); // get lock

    /* Sorry, I made a editing mistake the next sentence and have modified.
     * Previous my code is pthread_cond_wait(&test.cond);  
     */
    pthread_cond_wait(&test.cond, &test.mutex); 

    printf("hello\n");
    pthread_mutex_unlock(&test.mutex); // unlock

    return NULL;
}

int main(void)
{
    pthread_t tid;
    void *ret;

    if (pthread_mutex_init(&test.mutex, NULL) != 0) { // initialize mutex

    /* error */
    exit(2);
    }

    if (pthread_cond_init(&test.cond, NULL) != 0) {// initialize condtion variable

    /* error */
    exit(2);
    }

    if (pthread_create(&tid, NULL, thread1, NULL) != 0) {

    /* creation error*/
    exit(2);
   }

    /* wait for newly created thread run first */
    printf("sleep 1\n");
    sleep(3);

    pthread_mutex_lock(&test.mutex); // get lock
    pthread_cond_signal(&test.cond);

    /* sleep to test whether blocked thread would wake up 
     * when condition becomes true, but mutex is locked 
     */
    printf("sleep 2\n");
    sleep(3);

    pthread_mutex_unlock(&test.mutex); // unlock
    pthread_join(tid, (void **)&ret);

    return 0;
}

编辑:

  • 我尝试strace ./a.out,输出:
    futex(0x7f24e86419e0, FUTEX_WAIT_PRIVATE, 2, NULL) = -1 EAGAIN(资源暂时不可用+++
    +++ 被 SIGSEGV 杀死+++

  • 我修改了代码以使其正确调用 pthread_cond_wait()。输出是应该的。没有 SIGSEGV 了。这个程序能证明如果线程在pthread_cond_wait()中被阻塞,只有当pthread_cond_signal(或pthread_cond_broadcast)都被调用并获得互斥锁时它才会被唤醒,没有获得互斥锁它会像调用pthread_mutex_lock()一样阻塞???

最佳答案

我能够通过添加

让您的代码运行
#include <pthread.h>

然后将 &test.mutex 参数添加到 pthread_cond_wait 函数。

pthread_cond_wait(&test.cond, &test.mutex);

关于线程可以在接收到条件信号时唤醒但不能同时获得互斥锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38146129/

相关文章:

python - 试图将 python 嵌入到 tinycc 中,说 python 符号未定义

c - C 中的运算符结合性特别是前缀和后缀递增和递减

python - 是否可以使用 argparse 将正则表达式字符串作为参数传递给 Python CLI 工具?

c - 堆栈溢出与 C 中的指针

linux - 如何使用 awk 提取引用字段?

linux - 根据文件名中的数字索引对目录中的文件进行排序

java - 如果我有一个 Runnable 和一个实现线程的对象,我该如何使用 wait() 和 notification() ?

c - 在c程序中,当主线程终止时,整个进程是否终止?

Java套接字通信 "deadlock"

c - 多字符字符常量在 C 中有效吗?也许在 MS VC 中?