2011-03-22 84 views
0

我是C编程的初学者,我正试图在下面的程序中执行互斥锁,但我没有得到正确的输出。POSIX C程序(MUTEX程序)

#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); 
} 

按照上面的程序和我的理解,期望的输出将是18,但它给32

+0

欢迎来到Stack Overflow。请不要忘记[接受正确答案](http://meta.stackexchange.com/q/5234)来回答您的问题。 – jschmier 2011-03-24 21:09:37

回答

2

func使用a递增。我猜你的意思是增加i。实际上,在每个线程运行时,a必须处于其最终值8,因此您将四次添加8到counter

+0

亲爱的Marcelo,感谢您的回复。是的,它使用每个线程的ie 8的值,这意味着首先所有线程都是在使用ie8的最终值之后创建的。而不是这个,我想使用新值一个ie来自for循环的每次迭代。例如。当i的值为0时,a的值变为2,所以我希望线程[1]将使用2而不是8.同样,当i = 1时,a的值变为3,因此线程[2]的值为3.现在我希望很明显,请告诉我你是否需要我的更多澄清。提前致谢!!!。 – lekhraj 2011-03-23 09:22:02

+0

也许我的答案不清楚。用'counter + i'替换'counter + a'。另外,'a'不需要是全球性的;在main()中移动它。 – 2011-03-23 11:24:12

+0

亲爱的Marcelo,非常感谢您的回复,并且可以为我提供一些pthread教程的链接。再次感谢您的回复。 – lekhraj 2011-03-23 11:36:32

1

您在您的线程功能中没有使用i,但是a