这是我的服务器代码。执行老板工人。我指定线程工作者的数量。问题是有时它不回复我的客户,而且大多停留在接收状态。有时它会执行,但前提是客户端线程最少。客户端线程有时无法连接。任何人都可以指出错误。谢谢。
问问题
70 次
2 回答
1
检查点:
如何确保“freeThread+1”已为进程做好准备。无需检查,在您的代码中,您只需尝试锁定相应的互斥锁。
pthread_mutex_lock(&queue_mutex[freeThread+1]);
为什么你不断地发送信号?你不需要。一次就够了。此外,您为什么要提到
isThreadFree
flag?这不是安全线程。在竞争条件的情况下,它将被错误地引用。我认为您使用它来实现它,while
因为您已经遇到过这个问题。while(isThreadFree[freeThread+1]==true) { pthread_cond_signal(&queue_has_client[freeThread+1]); }
建议:
我认为您不需要使用多个互斥锁和cond_signal。clientQueue
相反,您只能对队列和条件使用一个互斥锁。
在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);
于 2018-03-02T21:51:42.303 回答
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
}
}
}
这几乎就是将套接字发送到子线程所需要做的所有事情。
于 2018-03-02T22:58:04.770 回答