In this post, we will see how to create threads in C language program using pthread. To study parallel/concurrent programming using any API, array addition (One dimensional) is always a better choice. It's because, in array addition, all additions are independent. You can use one thread to do one addition operation.
Here I have provided sample program for concurrent or parallel array addition using pthread. You have to include header file "pthread.h". Each thread is created using function pthread_create(). You can exit from particular thread by calling pthread_exit(NULL).
Go through the following program.
Program: (progbypthread.c)
#include <pthread.h>
#include <stdio.h>
int numofthreads=5;
int a[5]={1,2,3,4,5};
int b[5]={6,7,8,9,10};
int c[5];
void *arrayadd(void *threadid)
{
int tid;
tid = (int)threadid;
c[tid]=a[tid]+b[tid];
printf("The value of c[%d]=%d calculated by thread %d\n",tid,c[tid],tid);
// To exit from this thread
pthread_exit(NULL);
}
int main (int argc, char *argv[])
{
pthread_t threads[numofthreads];
int err;
int i;
for(i=0; i<numofthreads; i++)
{
err = pthread_create(&threads[i], NULL, arrayadd, (void *)i);
if(err)
{
printf("Error while creating thread\n");
return 0;
}
}
// To exit from main thread
pthread_exit(NULL);
}
How To Run:
To Compile:
gcc -pthread progbypthread.c
(Note: -pthread is used to use pthread library)
To Run:
./a.out
Output:
(Note: All array additions are getting computed simultaneously by different threads. That's why you may get result in any sequence.)
Previous: How To Create Threads in Java
Here I have provided sample program for concurrent or parallel array addition using pthread. You have to include header file "pthread.h". Each thread is created using function pthread_create(). You can exit from particular thread by calling pthread_exit(NULL).
Go through the following program.
Program: (progbypthread.c)
#include <pthread.h>
#include <stdio.h>
int numofthreads=5;
int a[5]={1,2,3,4,5};
int b[5]={6,7,8,9,10};
int c[5];
void *arrayadd(void *threadid)
{
int tid;
tid = (int)threadid;
c[tid]=a[tid]+b[tid];
printf("The value of c[%d]=%d calculated by thread %d\n",tid,c[tid],tid);
// To exit from this thread
pthread_exit(NULL);
}
int main (int argc, char *argv[])
{
pthread_t threads[numofthreads];
int err;
int i;
for(i=0; i<numofthreads; i++)
{
err = pthread_create(&threads[i], NULL, arrayadd, (void *)i);
if(err)
{
printf("Error while creating thread\n");
return 0;
}
}
// To exit from main thread
pthread_exit(NULL);
}
How To Run:
To Compile:
gcc -pthread progbypthread.c
(Note: -pthread is used to use pthread library)
To Run:
./a.out
Output:
(Note: All array additions are getting computed simultaneously by different threads. That's why you may get result in any sequence.)
Previous: How To Create Threads in Java
No comments:
Post a Comment