gpt4 book ai didi

c++ - Linux 上只有一个线程可能导致死锁或卡住程序?

转载 作者:IT王子 更新时间:2023-10-29 01:10:48 32 4
gpt4 key购买 nike

我正在做 C++ 多线程编程。我使用互斥量来读写队列以避免死锁。目前,我只为

启动 1 个线程
    pthread_mutex_lock(&the_mutex);

但是,在 GDB 中,我的代码在这里被卡住,它处于挂起状态。

为什么?只有一个线程!!!

谢谢

最佳答案

来自pthread_mutex_lock()手册页:

If the mutex type is PTHREAD_MUTEX_NORMAL, deadlock detection shall not be provided. Attempting to relock the mutex causes deadlock. If a thread attempts to unlock a mutex that it has not locked or a mutex which is unlocked, undefined behavior results.

If the mutex type is PTHREAD_MUTEX_DEFAULT, attempting to recursively lock the mutex results in undefined behavior. Attempting to unlock the mutex if it was not locked by the calling thread results in undefined behavior. Attempting to unlock the mutex if it is not locked results in undefined behavior.

底线:如果您尝试锁定一个已经锁定的互斥量,则完全有可能导致只有一个线程的死锁。

如果您想知道,在 Linux 上 PTHREAD_MUTEX_DEFAULT 通常是 PTHREAD_MUTEX_NORMAL 的同义词,后者又是默认互斥初始化器中使用的。

关于c++ - Linux 上只有一个线程可能导致死锁或卡住程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8024556/

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