gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:12:44 24 4
gpt4 key购买 nike

<分区>

我编写了一个程序来测试 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()一样阻塞???

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com