c - 从线程中断 main 中的 while 循环。 (C语言编程)

标签 c multithreading while-loop

我目前正在用 C 语言编写一个基本的客户端服务器消息传递程序。 我遇到的问题是服务器端代码。 代码的主要部分是一个 while 循环,用于检查来自客户端的新传入套接字连接。 如果客户端连接,则会生成一个新线程来处理传入消息。我使用的这个函数 tcp_wait_for_connection( server ); 是阻塞的。

所以我的问题是,是否可以中断这些线程之一的 while 循环,而不必使用 Exit() ,以便我可以关闭套接字

(我是 Stack Overflow 的新手,所以我不知道是否应该在此处发布完整的代码,我将最相关的部分放在下面,如果您需要更多内容,我将编辑该帖子。

谢谢

代码如下:

while(1) {

    client = (Socket *) malloc( sizeof(Socket) ); //allocate memory for the new client socket
    if ( client == NULL ){
        perror("Allocation of memory for the new client has failed");
        return 1;
    }
    //wait for a client to connect
    *client = tcp_wait_for_connection( server );
    printf("Incoming client connection\n");
    //get the socket descriptor for the new client socket
    sd = get_socket_descriptor(client);
    //insert the new client socket into the client list with the sd as ID
    InsertElement(&cl, (Element)client, sd);

    p_thread = (pthread_t *) malloc( sizeof(pthread_t) ); //allocate memory for the new thread handler
    if ( p_thread == NULL ){
        perror("Allocation of memory for the new thread has failed");
        return 1;
    }
    //insert the new thread handler into the thread handler list
    //with the sd of the corressponding client socket as ID
    InsertElement(&tl, (Element)p_thread, sd);
    //create the new thread
    pthread_create(p_thread, NULL, HandleClient, (void*)p_thread);

}
tcp_close( *client );
tcp_close( server );

最佳答案

不,你不能那样做。我建议您只调用从子线程关闭套接字的函数。使用 pthread_mutex 确保一次仅从一个线程执行此操作。另外,在 main 中,处理 tcp_wait_for_connection 中由于套接字正确关闭而发生的错误。

关于c - 从线程中断 main 中的 while 循环。 (C语言编程),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10920131/

相关文章:

c - 缓冲区溢出中的 Unname 系统调用

c - 我有一个关于打印的问题。 "EXC_BAD_ACCESS"

c - `pthread_mutex_trylock` 两个线程同时调用时阻塞

PHP 查询调用问题

java - 在 while 循环中更改 double 的值

c++ - 在 Linux/Unix 中同时使用 2 个程序访问 stdin

c - 命名管道,读取失败,文件描述符错误

Java作业执行多线程与executorservice?

multithreading - 如何将对堆栈变量的引用传递给线程?

c++ - 为什么循环只运行一次?