Thursday, April 25, 2013

pthread_exit example c c++


PTHREAD_EXIT(3)          BSD Library Functions Manual          PTHREAD_EXIT(3)

NAME
     pthread_exit -- terminate the calling thread

SYNOPSIS
     #include <pthread.h>

     void
     pthread_exit(void *value_ptr);

DESCRIPTION
     The pthread_exit() function terminates the calling thread and makes the value value_ptr available to
     any successful join with the terminating thread.  Any cancellation cleanup handlers that have been
     pushed and are not yet popped are popped in the reverse order that they were pushed and then executed.
     After all cancellation handlers have been executed, if the thread has any thread-specific data, appro-
     priate destructor functions are called in an unspecified order.  Thread termination does not release
     any application visible process resources, including, but not limited to, mutexes and file descriptors,
     nor does it perform any process level cleanup actions, including, but not limited to, calling atexit()
     routines that may exist.

     An implicit call to pthread_exit() is made when a thread other than the thread in which main() was
     first invoked returns from the start routine that was used to create it. The function's return value
     serves as the thread's exit status.

     The behavior of pthread_exit() is undefined if called from a cancellation handler or destructor func-
     tion that was invoked as the result of an implicit or explicit call to pthread_exit().

     After a thread has terminated, the result of access to local (auto) variables of the thread is unde-
     fined.  Thus, references to local variables of the exiting thread should not be used for the
     pthread_exit() value_ptr parameter value.

     The process will exit with an exit status of 0 after the last thread has been terminated.  The behavior
     is as if the implementation called exit() with a zero argument at thread termination time.

RETURN VALUES
     The pthread_exit() function cannot return to its caller.

ERRORS
     None.

SEE ALSO
     _exit(2), exit(3), pthread_create(3), pthread_join(3)

STANDARDS
     pthread_exit() conforms to ISO/IEC 9945-1:1996 (``POSIX.1'').

Example of pthread_exit


#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

void *t_function(void *data)
{
    int num = *((int *)data);
    int i = 0;
    while(1)
    {
        if (i == 3)
            pthread_exit(0);
        printf("loop %d\n", i);
        i++;
        sleep(1);
    }
}

int main()
{
    pthread_t p_thread;
    int thr_id;
    int status;
    int a = 100;


    thr_id = pthread_create(&p_thread, NULL, t_function, (void *)&a);
    if (thr_id < 0)
    {
        perror("thread create error : ");
        exit(0);
    }
    pthread_join(p_thread, (void **)&status);
    return 0;
}