gpt4 book ai didi

使用线程的并发 TCP 服务器

转载 作者:可可西里 更新时间:2023-11-01 02:44:56 26 4
gpt4 key购买 nike

我正在尝试创建一个并发 TCP 服务器,它接受多个(N 个连接),其中 N 是已知的。(例如 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 节以了解如何使用锁定和接受。

最佳答案

The program comes to an end after calling the thread_function()

问题是,在您创建线程后,主线程失败并结束程序。您应该调用 pthread_join


你的方法有问题。在您的代码中,您锁定 mlock 然后您 accept(2)。您正在关键部分调用阻塞函数。这严重限制了并行性,从而破坏了线程的大部分目的。

您可以尝试一种方法,其中主线程接受并将新套接字分派(dispatch)给线程。

关于使用线程的并发 TCP 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15003105/

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