In this example, we will show you how to create a thread in C programming.
Create Thread in C with Example
In this example, we will be creating a thread to perform a task. In this task, we will display the sequence numbers from 1 to 5. The focus of this recipe is to learn how a thread is created and how the main thread is asked to wait until the thread finishes its task.
Let's create a file named createthread.c and add the following source code to it:
#include <stdio.h> #include <stdlib.h> #include <pthread.h> void *runThread(void *arg) { int i; printf("Running Thread \n"); for(i=1;i<=5;i++) printf("%d\n",i); return NULL; } int main() { pthread_t tid; printf("In main function\n"); pthread_create(&tid, NULL, runThread, NULL); pthread_join(tid, NULL); printf("Thread over\n"); return 0; }
To compile and run the above C program, you can use C Programs Compiler Online tool.
Output:
In main function Running Thread 1 2 3 4 5 Thread over
Comments
Post a Comment