El hilo no termina (aunque estoy llamando a 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?

preguntado el 27 de noviembre de 13 a las 01:11

A thread should exit and not return value. Please change your return NULL a pthread_exit() and your code should work fine. -

@Ganesh Calling return is perfectly valid. return foo; es equivalente a pthread_exit(foo); a menos que the thread in question is the main thread. -

1 Respuestas

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 tampón.

respondido 27 nov., 13:01

Although I'm guessing you probably want a newline in that printf() anyway, I would also put a fflush(stdout); entre las printf() y return in order to be certain it flushes the buffer. stdout gets flushed every time there is a newline by convention, but I'm not sure there's any standard that requires it. In other words, I think it would be legitimate for an OS no to flush the buffer when there is a newline; it just happens that the ones people use most do. - david lillethun

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.