Collin
Collin

Reputation: 1875

Thread not finishing (even though I'm calling pthread_join)

So strange issue. I spawn my threads here. This should just keep looping until I kill it.

void accept_connections(int sock_fd)
{
    while(1)
    {
            /*Whole bunch of irrelevant stuff*/
        pthread_create(&(new_connect->thread), NULL, &thread_dispatch, new_connect);
        printf("Thread spawned.\n");
        pthread_join(new_connect->thread, NULL);
            /*Exit when catches a sigint */
    }
}

And the function the pthreads run:

void* thread_dispatch(void* new_connect)
{

    printf("Thread working.\n");

    http_t *http = malloc(sizeof(http_t));

    int bytes_read = http_read(http, fd);

    printf("read %d\n",bytes_read); //this prints
    printf("status %s\n",http->status); //this prints
    printf("body %s\n",http->body); //this prints
    const char* get_status = http_get_status(http);
    char* filename = process_http_header_request(get_status);
    printf("filename: %s", filename); //this doesn't print unless I do exit(1) on next line
    return NULL;
}
  1. why doesn't the last statement get printed? I'm calling pthread_join which should wait for the thread to return, and then terminate, right?

  2. Are my threads being terminated correctly this way?

Upvotes: 0

Views: 707

Answers (1)

Macattack
Macattack

Reputation: 1990

Your last line isn't printing because stdout is line buffered and you don't have a newline (\n) in that last printf(). exit() is likely flushing the stdout buffer.

Upvotes: 3

Related Questions