Creating a simple thread in Linux using pthread library api’s

 $ vim simple-linux-thread-using-pthread.c 
[java] #include <stdio.h> #include <stdlib.h> #include <pthread.h> void *functioncalledbythread(void *arg) { int count = 0, i; int *passed_value = (int*)arg; printf("Value passed to thread from main : %d \n", *passed_value); for(i=0; i<10; i++) { count++; sleep(1); } return NULL; } int main(int argc, char **argv) { int retval; pthread_t threadId; int pass_this_val = 5; printf("Creating simple thread\n"); if((retval = pthread_create(&threadId, NULL, &functioncalledbythread, (void *)&pass_this_val))) { printf("Thread creation failed: %d\n", retval); } printf("Waiting in main for thread to finish\n"); /* Wait till threads are complete before main continues.*/ pthread_join(threadId, NULL); printf("Thread execution finished, exiting from main program\n"); exit(0); } [/java]

The above program is self explanatory which creates a simple thread using pthread library API “pthread_create” which returns unique Thread ID in first argument threadId, and we pass two other arguments, a function pointer (functioncalledbythread) which points to the function called by the thread when it executes and void pointer which we can use to pass the values to the called function from main process to thread. (pass_this_val)

At the end we used pthread_join to make sure we wait in main application to let the thread complete its work before the main application terminates.

 $ gcc -o simple-linux-thread-using-pthread simple-linux-thread-using-pthread.c -lpthread 
 $ ./simple-linux-thread-using-pthread Creating simple thread
Waiting in main for thread to finish
Value passed to thread from main : 5 
Thread execution finished, exiting from main program

Leave a Comment