In: Computer Science
C Programming language problem
I need to write a program which uses several threads (like 8
threads for example) to sum up a number. The following program is
using 1 thread but I need several threads to compile it. There was
a hint saying that using multiple separate for loop and combining
them will make a multi-threaded program.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
int sum; // this data is shared by the threads
void *runner(void *param); // threads call this
function
int main(int argc, char *argv[])
{
pthread_t tid; // thread identifier
pthread_attr_t attr; // set of thread attributes
// set the default attributes of the thread
pthread_attr_init(&attr);
// create the thread
pthread_create(&tid, &attr, runner, argv[1]);
// wait for the thread to exit
pthread_join(tid, NULL);
printf("Sum = %d\n", sum);
}
void *runner(void *param)
{
int i, upper = atoi(param);
sum = 0;
for (int i = 1; i <= upper; i++)
sum += i;
pthread_exit(0);
}
HI,
Just edited your program for multithread program.i just added a loop to iterate thread ...you can set threads value hardcoded or can get it as command line argument by argv[1] .
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
int sum,i; // this data is shared by the threads
void *runner(void *param); // threads call this function
int main(int argc, char *argv[])
{
pthread_t tid; // thread identifier
pthread_attr_t attr; // set of thread attributes
// set the default attributes of the thread
pthread_attr_init(&attr);
// create the thread
//pthread_create(&tid, &attr, runner, argv[1]);
for (i = 0; i < 8; i++) {
printf("i = %d\n", i);
pthread_create(&tid, &attr, runner, argv[1]);
// wait for the thread to exit
pthread_join(tid, NULL);
}
printf("Sum = %d\n", sum);
//pthread_exit(0);
return 0;
}
void *runner(void *param)
{
int i, upper = atoi(param);
sum = 0;
for (int i = 1; i <= upper; i++)
sum += i;
printf("sum runner = %d\n", sum);
pthread_exit(0);
}