gpt4 book ai didi

c - 多线程客户端服务器执行有时不会结束

转载 作者:行者123 更新时间:2023-11-30 14:50:18 25 4
gpt4 key购买 nike

这是我的服务器代码。表演老板 worker 。我指定线程的工作线程数。问题是有时它不会回复我的客户并且大部分停留在接收状态。有时它会执行,但前提是客户端线程最少。客户端线程有时无法连接。谁能指出错误。谢谢。

最佳答案

检查点:

  1. 如何确保“freeThread+1”已为该进程做好准备。无需检查,在代码中,您只需尝试锁定相应的互斥锁。

    pthread_mutex_lock(&queue_mutex[freeThread+1]);
  2. 为什么你要连续发送信号?你不需要。只要一次就够了。此外,为什么您提到 isThreadFree 标志?这不是安全线程。如果出现竞争条件,则会被错误引用。我认为您使用 while 来实现此操作,因为您已经遇到过此问题。

    while(isThreadFree[freeThread+1]==true) {
    pthread_cond_signal(&queue_has_client[freeThread+1]);
    }

建议:我认为您不需要使用多个互斥锁和 cond_signal。相反,您只能对队列 clientQueue 和 cond 使用一个互斥体。

main()函数中:

pthread_mutex_lock(&queue_mutex);
p = enqueue(clientQueue, client_sock);
pthread_mutex_unlock(&queue_mutex);
pthread_cond_signal(&queue_has_client);

worker()函数中:

while (is_empty_queue(clientQueue)) {
pthread_cond_wait(&queue_has_client,&queue_mutex);
}
dequeue(clientQueue, &helper);
if (!is_empty_queue(clientQueue))
wake_up_other_thread = true;
pthread_mutex_unlock(&queue_mutex);
if (wake_up_other_thread) // to wake up other threads to serve the enqueued clients
pthread_cond_signal(&queue_has_client);

关于c - 多线程客户端服务器执行有时不会结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49070767/

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