簡體   English   中英

如何正確終止pthread?

[英]How to properly terminate a pthread?

我有一個TCP回顯服務器,該服務器為連接到它的每個客戶端創建一個pthread。 對於每個連接,我都有一個遞增的變量nbOfClients 當客戶端關閉其連接時,我會檢測到該連接並減少客戶端數量。 但是,服務器一直認為客戶端還活着,並繼續嘗試從套接字讀取/寫入。 我猜想那是由於創建客戶端的線程pthread_cancel ,我試圖使用pthread_cancel殺死該線程,但全部無效。 我想殺死與某個關閉其連接的客戶端關聯的pthread。 我該怎么辦?

這是我的代碼:

static int nbOfClients = 0;

static  pthread_t tid;

int main (int argc, char *argv[]) {

    int bytes_to_read, arg, listen_sd, new_conn, sockfd, client_len, port;
    struct sockaddr_in server, client_addr;
    char *bp, buf[BUFLEN];
    ssize_t n;


    sockfd = 0;

    switch(argc) {
        case 1:
          port = SERVER_TCP_PORT;   // Use the default port
          break;
        case 2:
          port = atoi(argv[1]); // Get user specified port
          break;
        default:
          fprintf(stderr, "Usage: %s [port]\n", argv[0]);
          exit(1);
    }

    // Create a stream socket
    if ((listen_sd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
        error("Cannot Create Socket!");

    // set SO_REUSEADDR so port can be resused imemediately after exit, i.e., after CTRL-c
    arg = 1;
    if (setsockopt (listen_sd, SOL_SOCKET, SO_REUSEADDR, &arg, sizeof(arg)) == -1)
        error("setsockopt");

    // Bind an address to the socket
    bzero((char *)&server, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(port);
    server.sin_addr.s_addr = htonl(INADDR_ANY); // Accept connections from any client

    if (bind(listen_sd, (struct sockaddr *)&server, sizeof(server)) == -1)
        error("bind error");

    listen(listen_sd, MAX_CONNECTIONS); ///put a define constant indicating the maximum number of clients #define NB_CLIENTS 3

    while (TRUE) {
        client_len = sizeof(client_addr);
        if ((new_conn = accept(listen_sd, (struct sockaddr *) &client_addr, (socklen_t *)&client_len)) == -1)
          error("accept error");

        if(new_conn > 0) {
            if(nbOfClients < MAX_CONNECTIONS) {
                printf("just here\n");
                printf(">> Initializing remote address: %s\n", inet_ntoa(client_addr.sin_addr));
                nbOfClients++;


                fclose(fp);

                printf("Connections to date: %u \n",nbOfClients);

                printf("make thread\n");
                pthread_create(&tid,NULL,&echo, (void *)new_conn);
                printf("had thread\n");
            }
            else {
                printf("connection limit reached\n");
                if(send(new_conn, "Server full!\n", 13, 0) == -1)
                    perror("send");
                close(new_conn);
            }
        }
    }

    return(0);
}

void * echo(void *arg) {
    char buf[BUFSIZE]; /* message buffer */
    int n, i = 0;

    bzero(buf, BUFSIZE);
    if(send((int)arg, "Welcome!!\n", 20, 0) == -1)
        perror("send");

    detect_closed_connection(arg);

    while(TRUE) {
        n = read((int)arg, buf, BUFSIZE);

        /**read: read input string from the client*/
        if(n < 0) {
            perror("error reading from socket");
        }

        printf("Server received from client, %d bytes: %s\n", n, buf);

        /**write: echo the input string in UPPERCASE back to the client*/

        int len = strlen(buf);
        for(i = 0; buf[i]; i++)
            buf[i] = toupper(buf[i]);

        n = write((int)arg, buf, len);
        if(n < 0) {
            error("ERROR writing to socket");
        }
    }
}

void detect_closed_connection(void * listenSocket) {
    struct pollfd pfd;
    pfd.fd = (int)listenSocket;
    pfd.events = POLLIN | POLLHUP | POLLRDNORM;
    pfd.revents = 0;
    while(pfd.revents == 0) {
        if(poll(&pfd, 1, 100) > 0) {
            // if result > 0, this means that there is either data available on the
            // socket, or the socket has been closed
            char buffer[32];
            if (recv((int)listenSocket, buffer, sizeof(buffer), MSG_PEEK | MSG_DONTWAIT) == 0) {
                // if recv returns zero, that means the connection has been closed:

                nbOfClients--;
                pthread_cancel(tid);

            }
        }
    }
}

謝謝。

您應該在為客戶端提供服務的線程中檢查read()是否返回0 ,因為如果對等方(此處的客戶端)關閉了連接,則read()返回0

在這行之后

n = read((int)arg, buf, BUFSIZE);

if (0 == n)
{
  fprintf(stderr, "The client closed the connection.\n");
  break;
}

就在線程函數離開之前,您可以添加該語句以減少正在運行的線程數。


還應注意,所有“客戶端”線程以及主線程會同時訪問nbOfClients ,因此應保護其訪問,例如通過使用互斥鎖。


還有另一個問題,因為對讀取的緩沖區的strlen()的調用期望緩沖區為0終止,即使您發送了0終止的“字符串”,也不一定需要這種情況。 read()可能會返回客戶端發送的“字符串”,而不是一部分。 因此,循環遍歷read()直到接收到0終止符。


不要通過調用pthread_cancel()使線程本身結束,而應使用pthread_exit()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM