How to work with Multi-Thread in C Programming? - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Random Posts

How to work with Multi-Thread in C Programming?

Share This

We know that Linux or Unix systems are multi-user and multi-tasking environments. Hence the processes in these environments can cooperate with each other. In a multi-threaded system, generally, threads share a segment of memory instead of allocating memory for each thread separately.
Source code of Multi-Threaded Program
#include <pthread.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #define NO_OF_THREADS 3 void *my_thread_function(void *arg); char msg[] = "My Multi-Thread Program"; int main(void) { int i, length; char *str; pthread_t mythreads[NO_OF_THREADS]; void *thread_result; for(i = 0; i < NO_OF_THREADS; i++) { length = snprintf( NULL, 0, "%d", i); str = malloc( length + 1 ); snprintf( str, length + 1, "%d", i); if (pthread_create(&mythreads[i], NULL, my_thread_function, (void *)str)) { printf("\nError in creating a thread!"); exit(EXIT_FAILURE); } } printf("\nWaiting for the thraed to finish...."); for(i = 0; i < NO_OF_THREADS; i++) { if (pthread_join(mythreads[i], &thread_result)) { printf("Error in joining this thread!"); exit(EXIT_FAILURE); } printf("\nThread joined successfully and it returned %s\n", (char *)thread_result); } exit(EXIT_SUCCESS); printf("\nAll the threads completed!"); } void *my_thread_function(void *arg) { int i; printf("my_thread_function has been started. Argument is %s\n", (int *)arg); for (i = 0; i < 5; i++) { printf("I am in a thread %s !\n", (char *)arg); sleep(1); strcpy(msg, "Bye!"); } pthread_exit("my_thread_function is being completed."); }

Compile it as

$ gcc mythreadtest.c -o mythreadtest -lpthread

Run it as

$ ./mythreadtest



Happy Exploring!

No comments:

Post a Comment