user3076313
user3076313

Reputation:

pthread loop doesn't immediately exit

Basically I want the program to exit when I send the "exit" command. As of now once the thread_callback function finishes after the exit command is sent the main loop does not immediately exit, instead it exits on the next client connection. Any idea how I could solve this?

I do not wish to use pthread_join or the exit function.

Thanks.

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;
}

Upvotes: 0

Views: 115

Answers (1)

Novak
Novak

Reputation: 2768

You should pass the server_socket to the thread as well, then:

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

shutdown will make accept to return.

Upvotes: 1

Related Questions