Multiple Threads in C with Example

In this example, you will learn how to multitask by executing two threads in parallel. Both of the threads will do their tasks independently. As the two threads will not be sharing a resource, there will not be a situation of race condition or ambiguity. 

The CPU will execute any thread randomly at a time, but finally, both of the threads will finish the assigned task. The task that the two threads will perform is displaying the sequence of numbers from 1 to 5.

Multiple Threads in C with Example

Let's create a file named twothreads.c and add the following source code to it:
#include<pthread.h>
#include<stdio.h>

void *runThread1(void *arg){
	int i;
    	printf("Running Thread 1\n"); 
	for(i=1;i<=5;i++)
		printf("Thread 1 - %d\n",i);
}

void *runThread2(void *arg){
	int i;
    	printf("Running Thread 2\n"); 
	for(i=1;i<=5;i++)
		printf("Thread 2 - %d\n",i);
}

int main(){
	pthread_t tid1, tid2;
	pthread_create(&tid1,NULL,runThread1,NULL);
	pthread_create(&tid2,NULL,runThread2,NULL);
	pthread_join(tid1,NULL);
	pthread_join(tid2,NULL);
    	printf("Both threads are over\n"); 
	return 0;
}

To compile and run the above C program, you can use C Programs Compiler Online tool.

Output:

Running Thread 1
Running Thread 2
Thread 2 - 1
Thread 2 - 2
Thread 2 - 3
Thread 2 - 4
Thread 2 - 5
Thread 1 - 1
Thread 1 - 2
Thread 1 - 3
Thread 1 - 4
Thread 1 - 5
Both threads are over



Comments