Pthread join in linux

Pthread join in linux

NAME

pthread_join - join with a terminated thread

SYNOPSIS

#include pthread.h> int pthread_join(pthread_t thread, void **retval); Compile and link with -pthread.

DESCRIPTION

The pthread_join() function waits for the thread specified by thread to terminate. If that thread has already terminated, then pthread_join() returns immediately. The thread specified by thread must be joinable. If retval is not NULL, then pthread_join() copies the exit status of the target thread (i.e., the value that the target thread supplied to pthread_exit(3)) into the location pointed to by retval. If the target thread was canceled, then PTHREAD_CANCELED is placed in the location pointed to by retval. If multiple threads simultaneously try to join with the same thread, the results are undefined. If the thread calling pthread_join() is canceled, then the target thread will remain joinable (i.e., it will not be detached).

RETURN VALUE

On success, pthread_join() returns 0; on error, it returns an error number.

ERRORS

EDEADLK A deadlock was detected (e.g., two threads tried to join with each other); or thread specifies the calling thread. EINVAL thread is not a joinable thread. EINVAL Another thread is already waiting to join with this thread. ESRCH No thread with the ID thread could be found.

ATTRIBUTES

For an explanation of the terms used in this section, see attributes(7). ┌───────────────┬───────────────┬─────────┐ │InterfaceAttributeValue │ ├───────────────┼───────────────┼─────────┤ │pthread_join() │ Thread safety │ MT-Safe │ └───────────────┴───────────────┴─────────┘

CONFORMING TO

NOTES

After a successful call to pthread_join(), the caller is guaranteed that the target thread has terminated. The caller may then choose to do any clean-up that is required after termination of the thread (e.g., freeing memory or other resources that were allocated to the target thread). Joining with a thread that has previously been joined results in undefined behavior. Failure to join with a thread that is joinable (i.e., one that is not detached), produces a "zombie thread". Avoid doing this, since each zombie thread consumes some system resources, and when enough zombie threads have accumulated, it will no longer be possible to create new threads (or processes). There is no pthreads analog of waitpid(-1, &status, 0), that is, "join with any terminated thread". If you believe you need this functionality, you probably need to rethink your application design. All of the threads in a process are peers: any thread can join with any other thread in the process.

EXAMPLE

SEE ALSO

pthread_cancel(3), pthread_create(3), pthread_detach(3), pthread_exit(3), pthread_tryjoin_np(3), pthreads(7)

COLOPHON

This page is part of release 5.05 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at https://www.kernel.org/doc/man-pages/.

© 2019 Canonical Ltd. Ubuntu and Canonical are registered trademarks of Canonical Ltd.

Читайте также:  Unlock bootloader xiaomi linux

Источник

Pthread join in linux

NAME

pthread_join - wait for thread termination

SYNOPSIS

#include pthread.h> int pthread_join(pthread_t thread, void **value_ptr); 

DESCRIPTION

The pthread_join() function shall suspend execution of the calling thread until the target thread terminates, unless the target thread has already terminated. On return from a successful pthread_join() call with a non-NULL value_ptr argument, the value passed to pthread_exit() by the terminating thread shall be made available in the location referenced by value_ptr. When a pthread_join() returns successfully, the target thread has been terminated. The results of multiple simultaneous calls to pthread_join() specifying the same target thread are undefined. If the thread calling pthread_join() is canceled, then the target thread shall not be detached. It is unspecified whether a thread that has exited but remains unjoined counts against .

RETURN VALUE

If successful, the pthread_join() function shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

The pthread_join() function shall fail if: EINVAL The implementation has detected that the value specified by thread does not refer to a joinable thread. ESRCH No thread could be found corresponding to that specified by the given thread ID. The pthread_join() function may fail if: EDEADLK A deadlock was detected or the value of thread specifies the calling thread. The pthread_join() function shall not return an error code of [EINTR]. The following sections are informative. 

EXAMPLES

An example of thread creation and deletion follows: typedef struct  int *ar; long n; > subarray; void * incer(void *arg)  long i; for (i = 0; i  ((subarray *)arg)->n; i++) ((subarray *)arg)->ar[i]++; > int main(void)  int ar[1000000]; pthread_t th1, th2; subarray sb1, sb2; sb1.ar = &ar[0]; sb1.n = 500000; (void) pthread_create(&th1, NULL, incer, &sb1); sb2.ar = &ar[500000]; sb2.n = 500000; (void) pthread_create(&th2, NULL, incer, &sb2); (void) pthread_join(th1, NULL); (void) pthread_join(th2, NULL); return 0; > 

APPLICATION USAGE

RATIONALE

The pthread_join() function is a convenience that has proven useful in multi-threaded applications. It is true that a programmer could simulate this function if it were not provided by passing extra state as part of the argument to the start_routine(). The terminating thread would set a flag to indicate termination and broadcast a condition that is part of that state; a joining thread would wait on that condition variable. While such a technique would allow a thread to wait on more complex conditions (for example, waiting for multiple threads to terminate), waiting on individual thread termination is considered widely useful. Also, including the pthread_join() function in no way precludes a programmer from coding such complex waits. Thus, while not a primitive, including pthread_join() in this volume of IEEE Std 1003.1-2001 was considered valuable. The pthread_join() function provides a simple mechanism allowing an application to wait for a thread to terminate. After the thread terminates, the application may then choose to clean up resources that were used by the thread. For instance, after pthread_join() returns, any application-provided stack storage could be reclaimed. The pthread_join() or pthread_detach() function should eventually be called for every thread that is created with the detachstate attribute set to PTHREAD_CREATE_JOINABLE so that storage associated with the thread may be reclaimed. The interaction between pthread_join() and cancellation is well-defined for the following reasons: * The pthread_join() function, like all other non-async-cancel-safe functions, can only be called with deferred cancelability type. * Cancellation cannot occur in the disabled cancelability state. Thus, only the default cancelability state need be considered. As specified, either the pthread_join() call is canceled, or it succeeds, but not both. The difference is obvious to the application, since either a cancellation handler is run or pthread_join() returns. There are no race conditions since pthread_join() was called in the deferred cancelability state.

FUTURE DIRECTIONS

SEE ALSO

pthread_create() , wait() , the Base Definitions volume of IEEE Std 1003.1-2001,

Источник

ОПИСАНИЕ

Функция pthread_join() ждёт завершения нити, указанной в thread. Если нить уже завершила работу, то pthread_join() завершается сразу. Нить, задаваемая в thread, должна позволять присоединение.

Если retval не равно NULL, то pthread_join() копирует код выхода нити назначения (т. е., значение, которое нить назначения передала через pthread_exit(3)) в расположение по указателю retval. Если нить назначения была отменена, то в расположение по указателю retval помещается значение PTHREAD_CANCELED.

Если к одной нити одновременно пытаются присоединиться несколько нитей, то результат не определён. Если нити вызвавшая pthread_join(), отменяется, то нить назначения остаётся доступной для присоединения (т. е., не будет отсоединена).

ВОЗВРАЩАЕМОЕ ЗНАЧЕНИЕ

При успешном выполнении pthread_join() возвращается 0; при ошибке возвращается номер ошибки.

ОШИБКИ

EDEADLK Обнаружена взаимная блокировка (например, когда две нити пытаются присоединиться друг к другу); или в thread указана вызывающая нить. EINVAL Нить thread не является присоединяемой. EINVAL Другая нить уже ждёт присоединения к этой нити. ESRCH Нить с идентификатором thread не найдена.

АТРИБУТЫ

Описание терминов данного раздела смотрите в attributes(7).

Интерфейс Атрибут Значение
pthread_join() Безвредность в нитях MT-Safe

СТАНДАРТЫ

HISTORY

ЗАМЕЧАНИЯ

После успешного выполнения pthread_join() вызывающему гарантируется, что целевая нить завершила работу. Вызывающий теперь может сделать нужные после завершения нити операции по очистке (например, освободить память или другие ресурсы, которые использовались целевой нитью).

Присоединение к нити, из которой уже был получен результат присоединения, приводит к непредсказуемым последствиям.

Ошибка присоединения к нити, доступной для присоединения (т. е., не отсоединённой), создаёт «нить-зомби». Лучше их избегать, так как нить-зомби потребляет некоторые системные ресурсы, и когда накапливается много нитей-зомби становится невозможно создание новых нитей (или процессов).

Аналога waitpid(-1, &status, 0) в pthreads не существует, то есть присоединиться к любой завершившейся нити». Если вы уверены, что вам нужна такая возможность, то, вероятно, стоит пересмотреть проект приложения.

Все нити в процессе равноправны: любая нить может присоединиться к любой другой нити процесса.

ПРИМЕРЫ

СМ. ТАКЖЕ

ПЕРЕВОД

Русский перевод этой страницы руководства был сделан Alexey, Azamat Hackimov , kogamatranslator49 , Kogan, Max Is , Yuri Kozlov и Иван Павлов

Этот перевод является бесплатной документацией; прочитайте Стандартную общественную лицензию GNU версии 3 или более позднюю, чтобы узнать об условиях авторского права. Мы не несем НИКАКОЙ ОТВЕТСТВЕННОСТИ.

Если вы обнаружите ошибки в переводе этой страницы руководства, пожалуйста, отправьте электронное письмо на man-pages-ru-talks@lists.sourceforge.net.

Powered by archmanweb, using mandoc for the conversion of manual pages.

The website is available under the terms of the GPL-3.0 license, except for the contents of the manual pages, which have their own license specified in the corresponding Arch Linux package.

Источник

Pthread join in linux

Compile and link with -pthread .

DESCRIPTION

The pthread_join () function waits for the thread specified by thread to terminate. If that thread has already terminated, then pthread_join () returns immediately. The thread specified by thread must be joinable.

If retval is not NULL, then pthread_join () copies the exit status of the target thread (i.e., the value that the target thread supplied to pthread_exit (3)) into the location pointed to by *retval . If the target thread was canceled, then PTHREAD_CANCELED is placed in *retval .

If multiple threads simultaneously try to join with the same thread, the results are undefined. If the thread calling pthread_join () is canceled, then the target thread will remain joinable (i.e., it will not be detached).

RETURN VALUE


ERRORS

EDEADLK A deadlock was detected (e.g., two threads tried to join with each other); or thread specifies the calling thread. EINVAL thread is not a joinable thread. EINVAL Another thread is already waiting to join with this thread. ESRCH No thread with the ID thread could be found.

CONFORMING TO


NOTES

After a successful call to pthread_create (), the caller is guaranteed that the target thread has terminated.

Joining with a thread that has previously been joined results in undefined behavior.

Failure to join with a thread that is joinable (i.e., one that is not detached), produces a «zombie thread». Avoid doing this, since each zombie thread consumes some system resources, and when enough zombie threads have accumulated, it will no longer be possible to create new threads (or processes).

There is no pthreads analog of waitpid(-1, &status, 0) , that is, «join with any terminated thread». If you believe you need this functionality, you probably need to rethink your application design.

All of the threads in a process are peers: any thread can join with any other thread in the process.

Источник

Оцените статью
Adblock
detector