pthread_join() — Wait for a thread to end
Standards
Standards / Extensions | C or C++ | Dependencies |
---|---|---|
POSIX.4a |
both | POSIX(ON) |
Format
#define _OPEN_THREADS
#include <pthread.h>
int pthread_join(pthread_t thread, void **status);
SUSV3:
#define _UNIX03_THREADS
#include <pthread.h>
int pthread_join(pthread_t thread, void **status);
General description
Allows the calling thread to wait for the ending of the target thread.
pthread_t is the data type used to uniquely identify a thread. It is returned by pthread_create() and used by the application in function calls that require a thread identifier.
status contains a pointer to the status argument passed by the ending thread as part of pthread_exit(). If the ending thread terminated with a return, status contains a pointer to the return value. If the thread was canceled, status can be set to -1.
Returned value
If successful, pthread_join() returns 0.
If unsuccessful, pthread_join() returns -1 and sets
errno to one of the following values:
- Error Code
- Description
- EDEADLK
- A deadlock has been detected. This can occur if the target is directly or indirectly joined to the current thread.
- EINVAL
- The value specified by thread is not valid.
- ESRCH
- The value specified by thread does not refer to an undetached thread.
Notes:
- When pthread_join() returns successfully, the target thread has been detached.
- Multiple threads cannot use pthread_join() to wait for the same target thread to end. If a thread issues pthread_join() for a target thread after another thread has successfully issued pthread_join() for the same target thread, the second pthread_join() will be unsuccessful.
- If the thread calling pthread_join() is canceled, the target thread is not detached.
Special behavior for Single UNIX Specification, Version 3: If unsuccessful, pthread_join() returns an error number to indicate the error.
Example
CELEBP32
/* CELEBP32 */
#define _OPEN_THREADS
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
void *thread(void *arg) {
char *ret;
printf("thread() entered with argument '%s'\n", arg);
if ((ret = (char*) malloc(20)) == NULL) {
perror("malloc() error");
exit(2);
}
strcpy(ret, "This is a test");
pthread_exit(ret);
}
main() {
pthread_t thid;
void *ret;
if (pthread_create(&thid, NULL, thread, "thread 1") != 0) {
perror("pthread_create() error");
exit(1);
}
if (pthread_join(thid, &ret) != 0) {
perror("pthread_create() error");
exit(3);
}
printf("thread exited with '%s'\n", ret);
}
Output:
thread() entered with argument 'thread 1'
thread exited with 'This is a test'