首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >POSIX C程序(MUTEX程序)

POSIX C程序(MUTEX程序)
EN

Stack Overflow用户
提问于 2011-03-22 19:59:13
回答 2查看 513关注 0票数 0

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

代码语言:javascript
复制
#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。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-03-22 20:09:40

func使用a来递增。我猜你的意思是通过i递增。实际上,在每个线程运行时,a必须达到其最终值8,因此您要在counter中添加4次8。

票数 2
EN

Stack Overflow用户

发布于 2011-03-22 20:11:21

您在线程函数中使用的不是i,而是a。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5390827

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档