C program to implement Multithreading-Multithreading in C

by

Posted on 05 October 2017

C is not a multithreaded language like Java but then you must be thinking how most of the Operating Systems like UNIX, Linux supports multithreading well the answer is POSIX threads usually referred to as pthreads. pthreads is an execution model that exists independently from a language, as well as a parallel execution model. It allows a program to control multiple different flows of work that overlap in time.

Don't know what is a thread? just read our article Thread Synchronization Program in Java-Multithreading   

Let us see a simple example based on pthreads. In this example, we will create a simple thread and run it.

#include<pthread.h>
#include<stdio.h>

void *mythread();	//thread prototype

int main(){
	pthread_t thread;
	//starting the thread
	pthread_create(&thread,NULL,mythread,NULL);
	//waiting for completion
	pthread_join(thread,NULL);
	
	
	return 0;
}

void *mythread(){
	printf("Thread Running");
}

Output:

Multithreading in C

Important points to note:

  • the pthread_create() function takes four parameters.
  • The first parameter is the pointer to the thread id.
  • The second argument is a pointer to a pthread_attr_t with parameters for the thread. You can safely just pass NULLmost of the time.
  • The third argument is the function name to call.
  • The fourth argument is function parameters if there are no parameters just pass in NULL.
  • pthread_join is similar to wait() in java it will wait for the completion of the thread.

Now let's see two threads executing simultaneously.

#include<pthread.h>
#include<stdio.h>

void *mythread1();	//thread prototype
void *mythread2();

int main(){
	pthread_t thread[2];
	//starting the thread
	pthread_create(&thread[0],NULL,mythread1,NULL);
	pthread_create(&thread[1],NULL,mythread2,NULL);
	//waiting for completion
	pthread_join(thread[0],NULL);
	pthread_join(thread[1],NULL);
	
	
	return 0;
}

//thread definition
void *mythread1(){
	int i;
	for(i=0;i<5;i++)
		printf("Thread 1 Running\n");
}
void *mythread2(){
	int i;
	for(i=0;i<5;i++)
		printf("Thread 2 Running\n");
}

Output:

Multithreading in C

Thank you for reading.

Tweet your queries and feedback to @PsychoCodes or leave a message on our Facebook page. You can also comment your questions below.

Also, don't forget to subscribe to our Newsletter.

If you like this article, then please share it and help us grow.


If You Love this article, You Should Consider:

  • Like us on Facebook
  • Follow us on Instagram
  • Follow us on Twitter
  • Subscribe to our Newsletter.
  • Let us know your suggestions and queries in the comments below.

Thank you for your Love and Support

Share your thoughts

Search
Adverstisement
Adverstisement