A pthread can be created using the function pthread_create(). It adds a new thread of control to the current process.
Syntax
int pthread_create(pthread_t *pid, const pthread_attr_t *tattr, void*(*start_routine)(void *), void *arg);
- pid - When pthread_create() is successful, the ID of the created thread is stored in the location referred to as pid.
- start_routine - It is the function with which the new thread begins execution.
- tattr - It has the necessary state behavior.
- arg - If we want to pass any arguments to the thread function, then this parameter can be used
Return Values
pthread_create() returns zero when the call completes successfully. Any other return value indicates that an error occurred. When any of the following conditions are detected, pthread_create() fails and returns the corresponding value.
- EAGAIN - A system limit is exceeded, such as when too many threads have been created.
- EINVAL - The value of tattr is invalid.
Example:
#include<stdio.h> #include<pthread.h> void * my_func(void * args) { printf("My thread function called\n"); } void main() { pthread_t pid; int ret; ret = pthread_create(&pid, NULL, &my_func, NULL); if(ret != 0) printf("pthread_create failed\n"); }
To compile the above program, we need to use the option -lpthread.
When the above program is executed one would expect the output to print "My thread function called" but it will not. It is because before the thread gets executed our calling thread gets exited. To overcome this we have to use the pthread_join function.
No comments:
Post a Comment