pthread循环不会立即退出

时间:2013-12-06 23:35:31

标签: c pthreads

基本上我希望程序在发送“exit”命令时退出。截至目前,一旦在发送退出命令后thread_callback函数完成,主循环不会立即退出,而是在下一个客户端连接上退出。知道如何解决这个问题吗?

我不想使用pthread_join或退出函数。

感谢。

void *thread_callback(void *client_data) {
  int client_id = *(int *)client_data;
  char some_buffer[BUFFER_SIZE];

  printf("thread %p\n", (void *)pthread_self());

  while (exit_flag != 1) {
    int len = recv(client_id, some_buffer, BUFFER_SIZE, 0);

    if (len > 0) {
        printf("%.*s\n", len, some_buffer);

        if (strcmp("exit", some_buffer) == 0)
            exit_flag = 1;
    }
  }

  pthread_exit(NULL);
}

int main(int argc, char **argv) {
  int server_socket;
  int client_socket;

  server_socket = create_tcp_server();

  while (exit_flag != 1) {
    pthread_t thread_id;

    client_socket = accept(server_socket, NULL, 0);

    if (client_socket > 0) {
        pthread_create(&thread_id, NULL, &thread_callback, (void *)&client_socket);
        pthread_detach(thread_id);
    }
  }

  return 0;
}

1 个答案:

答案 0 :(得分:1)

你也应该将server_socket传递给线程,然后:

if (strcmp("exit", some_buffer) == 0) {
      exit_flag = 1;
      shutdown(server_socket, 0);
}

shutdown会让accept返回。