POSIX C PROGRAM(MUTEX PROGRAM)
I am a beginner in C programming and I am trying to perform mutex on the program below, but I'm not getting the proper output.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define NUM_THREAD 4
void *func(void *p);
int counter=0,a=2;
pthread_mutex_t mutexsum = PTHREAD_MUTEX_INITIALIZER;
main()
{
int i,rc;
pthread_t threadid[NUM_THREAD];
for(i = 0; i< NUM_THREAD; i++)
{
a = a + i;
开发者_如何学编程 printf("Value of a is %d\n",a);
rc = pthread_create(&threadid[i],NULL,func,(void *)a);
if(rc)
{
printf("Error in thred creation thread[%d] %d",i,rc);
}
}
for(i = 0; i< NUM_THREAD; i++)
{
pthread_join(threadid[i],NULL);
}
printf("Final value of counter is %d\n",counter);
pthread_exit(NULL);
}
void *func(void *p)
{
int i;
i = (int) p;
pthread_mutex_lock(&mutexsum);
counter = counter+a;
printf("%d\n",counter);
pthread_mutex_unlock(&mutexsum);
pthread_exit(NULL);
}
As per the above program and my understanding, the desired output will be 18, but it's giving 32.
func
uses a
to increment. I'm guessing you meant to increment by i
. As it is, by the time each thread runs, a
must be at its final value of 8, so you are adding 8 to counter
four times.
You are not using i in your thread function, but a.
精彩评论