Problem: I have to increment x1 and x2 variable which should be done by separate threads and next increment of both variables should not be called until pr
The problem with your program is that you are synchronizing your threads to run in lockstep with each other. In each thread, at each iteration, a counter is incremented, and then two synchronization primitives are called. So, more than half the time in the loop body is spent on synchronization.
In your program, the counters really have nothing to do with each other, so they really should run independently of each other, which means each thread could actually do actual computing during their iterations rather than mostly synchronizing.
For the output requirements, you can allow each thread to put each sub-calculation into an array that the main thread can read from. The main thread waits for each thread to completely finish, and can then read from each array to create your output.
void *threadfunc1(void *parm)
{
int *output = static_cast(parm);
for (int i = 0; i < 10; ++i) {
x1++;
output[i] = x1;
}
return NULL ;
}
void *threadfunc2(void *parm)
{
int *output = static_cast(parm);
for (int i = 0; i < 10; ++i) {
x2++;
output[i] = x2;
}
return NULL ;
}
int main () {
int out1[10];
int out2[10];
pthread_create(&pth1, NULL, threadfunc1, out1);
pthread_create(&pth2, NULL, threadfunc2, out2);
pthread_join(pth1, NULL);
pthread_join(pth2, NULL);
int loop = 0;
while (loop < 9) {
// iterated as a step
loop++;
printf("Final : x1 = %d, x2 = %d\n", out1[loop], out2[loop]);
}
printf("Result : x1 = %d, x2 = %d\n", out1[9], out2[9]);
return 1;
}