Wednesday, April 24, 2013

pthread_create example c c++


NAME
     pthread_create -- create a new thread

SYNOPSIS
     #include <pthread.h>

     int
     pthread_create(pthread_t *restrict thread, const pthread_attr_t *restrict attr,
         void *(*start_routine)(void *), void *restrict arg);

DESCRIPTION
     The pthread_create() function is used to create a new thread, with attributes specified by attr, within
     a process.  If attr is NULL, the default attributes are used.  If the attributes specified by attr are
     modified later, the thread's attributes are not affected.  Upon successful completion, pthread_create()
     will store the ID of the created thread in the location specified by thread.

     Upon its creation, the thread executes start_routine, with arg as its sole argument.  If start_routine
     returns, the effect is as if there was an implicit call to pthread_exit(), using the return value of
     start_routine as the exit status.  Note that the thread in which main() was originally invoked differs
     from this.  When it returns from main(), the effect is as if there was an implicit call to exit(),
    using the return value of main() as the exit status.(pthread_create)

     The signal state of the new thread is initialized as:

           •   The signal mask is inherited from the creating thread.
           •   The set of signals pending for the new thread is empty.

RETURN VALUES
     If successful,  the pthread_create() function will return zero.  Otherwise, an error number will be
     returned to indicate the error.

ERRORS
     pthread_create() will fail if:

     [EAGAIN]           The system lacked the necessary resources to create another thread, or the system-
                        imposed limit on the total number of threads in a process [PTHREAD_THREADS_MAX]
                        would be exceeded.

     [EINVAL]           The value specified by attr is invalid.

Example of pthread_create
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

void *t_function(void *data)
{
    int id;
    int i = 0;
    id = *((int *)data);

    while(1)
    {
        printf("%d : %d\n", id, i);
        i++;
        sleep(1);
    }
}

int main()
{
    pthread_t p_thread[2];
    int thr_id;
    int status;
    int a = 1;
    int b = 2;

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

    thr_id = pthread_create(&p_thread[1], NULL, t_function, (void *)&b);
    if (thr_id < 0)
    {
        perror("thread create error : ");
        exit(0);
    }

    pthread_join(p_thread[0], (void **)&status);
    pthread_join(p_thread[1], (void **)&status);

    return 0;
}