简体   繁体   English

等待所有子线程完成(在C中)

[英]Wait for all child thread to finish (in C)

Code first 代码优先

while(running)
{
    memset(&tcp_client, 0, tcp_client_len);

    FD_ZERO(&readFDs);
    FD_SET(tcp_server_s, &readFDs);
    tv.tv_sec = 1;
    if(select(0, &readFDs, NULL, NULL, &tv))
    {
        if( (tcp_client_s = accept(tcp_server_s, (struct sockaddr *)&tcp_client,&tcp_client_len)) == INVALID_SOCKET )
        {
            cli_log(PROTO_TCP, LOG_ERROR, "(%d) accept() failed\n", WSAGetLastError());
            continue;
        }
        cli_log(PROTO_TCP, LOG_COMM, "(%s:%d) accepted connection\n", inet_ntoa(tcp_client.sin_addr), ntohs(tcp_client.sin_port));

        CreateThread(NULL, 0, tcp_thread, (LPVOID)tcp_client_s, 0, NULL);
    }
}

This is part of my TCP threads handler. 这是我的TCP线程处理程序的一部分。 What i would like to know is how to make it wait for all his child thread to finish before exiting when not running anymore (CTRL+C signal). 我想知道的是如何使其不再running (CTRL + C信号)退出之前等待所有子线程完成。

  1. Maintain a list of HANDLE s containing the handles of the successfully created threads (a HANDLE is the result of CreateThread() if successful). 维护一个HANDLE的列表,其中包含成功创建的线程的HANDLE CreateThread()如果成功,则HANDLECreateThread()的结果)。
  2. Use WaitForMultipleObjects() to join on each of the threads prior to application exit. 使用WaitForMultipleObjects()在应用程序退出之前加入每个线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM