2

我对 mutex / cond 等待类的这个简单包装器有疑问。我用它来保护已连接客户端的队列,并通知处于等待状态的线程有新的客户端连接,但应用程序因分段失败而崩溃

client_socket_fd = clients_for_threads_q.front();

仅在进行压力测试时(许多客户端已连接)

等待线程:

    MUTEXCONDSIGNAL_for_workers.lock();
    if ( clients_for_threads_q.empty() )
    {
        MUTEXCONDSIGNAL_for_workers.wait_signal();
    }

    client_socket_fd = clients_for_threads_q.front(); // CRASHED !!!!
    clients_for_threads_q.pop();
    MUTEXCONDSIGNAL_for_workers.unlock();

当然,clients_for_threads_q 在写作时受到保护

    MUTEXCONDSIGNAL_for_workers.lock();
    clients_for_threads_q.push (client_socket_fd);
    MUTEXCONDSIGNAL_for_workers.send_signal();
    MUTEXCONDSIGNAL_for_workers.unlock();
4

1 回答 1

4

pthread_cond_wait可以有虚假的唤醒。

当使用条件变量时,总是有一个布尔谓词涉及与每个条件相关联的共享变量等待如果线程应该继续,则该条件等待为真。可能会发生来自 pthread_cond_wait() 或 pthread_cond_timedwait() 函数的虚假唤醒。由于 pthread_cond_wait() 或 pthread_cond_timedwait() 的返回并不暗示该谓词的值,因此应在此类返回时重新评估谓词。

您需要将服务员if条件更改为循环:

while ( clients_for_threads_q.empty() )
{
    MUTEXCONDSIGNAL_for_workers.wait_signal();
}
于 2012-04-21T23:19:30.807 回答