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

问题描述 投票:0回答:2

这是我的服务器代码。表演老板工人。我指定线程的工作者数量。问题是,有时候它不会回复我的客户,而且大部分都是在接收时。有时它会执行但仅在客户端线程最小时执行。客户端线程有时无法连接。任何人都可以指出错误。谢谢。

c multithreading client-server threadpool worker-thread
2个回答
1
投票

检查点:

  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。相反,您只能使用一个互斥量作为队列clientQueueand 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);

0
投票

正如其他海报所提到的,您的代码太复杂了,无法将接受的套接字简单地传递给工作线程。

您所需要的只是一个队列,用于将套接字从主线程传递到任何可用的子线程。您尝试管理每个线程正在执行的操作,而不是实现线程安全队列。

这是一个非常简单的方法,使用管道作为队列:

static int socketPipe[ 2 ];

void *child_thread( void *arg );
{
    while ( 1 ) {
        int mySocket;
        size_t bytesRead = read( socketPipe[ 0 ], &mySocket, sizeof( mySocket ) );
        if ( bytesRead != sizeof( mySocket ) ) {
            // error
        }
        // now handle socket connection in mySocket
    }
    return( NULL );
}

int main( int argc, char **argv )
{
    // create socket pipe
    int rc = pipe( socketPipe );

    // create threads and listener socket

    // handle incoming connections and pass to child threads
    while ( 1 ) {
        int newConn = accept( mainSocket, &peer, &lenPeer )
        if ( incomingConnection != -1 ) {
            ssize_t written =
                write( socketPipe[ 1 ], &newConn , sizeof( newConn ) );
            // handle errors
        }
    }
}

这就是将套接字发送到子线程所需的全部内容。

© www.soinside.com 2019 - 2024. All rights reserved.