Nがわかっている複数(N接続)を受け入れる並行TCPサーバーを作成しようとしています(例:N = 8)。したがって、プリスレッドTCPサーバーを作成しようとしています。
....。
for(i=0;i<NUMBER_OF_CONNECTIONS;i++)
{
CreateThreads(i);
}
return 0;
}
//Create threads to handle the connection
void CreateThreads( int i )
{
pthread_create(&thread_tid[i], NULL, thread_function, (void *) i);
return;
}
void* thread_function(void *arg)
{
puts("In thread_function");
int client_soc,clilen;
struct sockaddr_in *clientaddr;
if( (clientaddr = malloc(addrlen)) == NULL)
printf("malloc Error\n");
printf("thread %d starting\n", (int) arg);
while(1)
{
clilen = sizeof(struct sockaddr_in);
pthread_mutex_lock(&mlock);
puts("Calling accept \n");
if ( (client_soc = accept(socket_desc, (struct sockaddr *)&clientaddr,(socklen_t*)&clilen)) < 0)
{
printf("accept error\n");
}
pthread_mutex_unlock(&mlock);
printf("Process Request...calling connection handler \n");
connection_handler(client_soc); /* process request */
close(client_soc);
}
}
//This will handle connection for each client
void *connection_handler(void *socket_desc)
{
//Receive and process.....
return 0;
}
上記のコードでは、スレッドが作成され、thread_function()が呼び出されますが、期待どおりに機能しません。thread_function()を呼び出した後、プログラムは終了し、それまでにいくつかのスレッドが作成されます。実際には、「N」個のスレッドを作成して、クライアントが接続するのを待ちます(accept()を使用)。接続したら、データの受信/収集(または)コマンドの送信などを行います。それがconnection_handler()を使用している理由ですが、その前に立ち往生しています。
誰かがthread_function()関数を修正しようと試みることはできますか?私はここで立ち往生しているようなものです。ありがとう。 更新プログラムはhttp://www.cse.fau.edu/~jie/research/publications/Publication_files/roussevwu.pdf に基づいてい ます 。ロックと受け入れの使用については、セクション3.2を参照してください。