How to get error code from pthread_join

The following code cannot create join pthreads, and the message "join failed" will be printed. How to get additional error information and call it?

pthread_t aThread[MAX_LENGTH];
    int errCode[MAX_LENGTH];
    char returnVal;    
for(int i = 0; i < MAX_LENGTH; i++)
    {

        if((errCode[i] = pthread_create(&aThread[i], NULL, &findMatch, &fpArgs)) != 0)
            printf("error creating thread %d\n", errCode[i]);
        if(!pthread_join(aThread[i], (void**)&returnVal))
            printf("join failed\n i is %d", i);
    }

EDIT: Really joined the return no errorand I made a mistake. If stat should not have !, because join returns a nonzero number if there is a problem that evaluates to true.

+4
source share
4 answers

I pointed this out in a comment, but it deserves to be strengthened.

Misuse returnVal

pthread_join api a void**, void*. void*, a void** . , . , , , NULL. , undefined . , sizeof(char), , , sizeof(void*), , , . :

pthread_join(aThread[i], NULL);

, void**, void* -proc. , pthread thread-proc :

void* thread_proc(void* args)
// ^----- this is what is stashed in the pthread_join second parameter

pthread_join 0 ; .


concurrency , . . , , , .. ( , ), . , , :

pthread_t aThread[MAX_LENGTH];
int errCode[MAX_LENGTH] = {0};

for (int i = 0; i < MAX_LENGTH; i++)
{
    if((errCode[i] = pthread_create(&aThread[i], NULL, &findMatch, &fpArgs)) != 0)
        printf("error creating thread %d, error=%d\n", i, errCode[i]);
}

for (int i = 0; i < MAX_LENGTH; i++)
{
    // note the check for errCode[i], which is only non-zero 
    //  if the i'th thread failed to start
    if(errCode[i] == 0)
    {
        errCode[i] = pthread_join(aThread[i], NULL))
        if (errCode[i] != 0)
            printf("error joining thread %d, error=%d\n", i, errCode[i]);
    }
}
+4

(.. pthread, , ), errno . .

int returnval;

if((returnval = pthread_join(aThread[i], (void**)&returnVal)) != 0)
{
    printf("error joining thread: %s\n", strerror(returnval));  //1st optiop

    perror("error joining thread:");  //2nd option

    printf("error joining thread: %m\n");  //3rd option

}

(1) strerror , , printf.

(2) perror , , errno. errno.

(3) glibc printf, %m, strerror, . .

, , , . , pthread_join.

+2

- ? :

    pthread_join() . ,     , .

   pthread_join() , :

 [EDEADLK]          A deadlock was detected or the value of thread speci-
                    fies the calling thread.

 [EINVAL]           The implementation has detected that the value speci-
                    fied by thread does not refer to a joinable thread.

 [ESRCH]            No thread could be found corresponding to that speci-
                    fied by the given thread ID, thread.
0

:

int retVal = pthread_create(&myThread, NULL,myThreadFn, NULL);
printf("error joining thread: %d\n", retVal);
0
source

All Articles