【问题标题】:Getting wrong value for ID in pthreads在 pthreads 中获取错误的 ID 值
【发布时间】:2015-03-16 22:19:25
【问题描述】:

我试图让我的输出成为

Starting Professor 1
Starting Professor 2
Starting Professor 3
...

但是当 num_professors = 2 时,我从来没有得到“Starting Professor 1”。我认为制作一个 id 数组可以保存整个 id 地址的传入,但显然不是。对于这个项目,我还有大约 70 件其他事情要做,并且在这个简单的事情上遇到障碍(可能需要几秒钟才能解决)至少可以说是非常令人沮丧的。非常感谢

void * professorFunc(void *p){
    sem_wait(&workAssignment);
    if(buffer == 0){
            buffer++;
            Professor *professor = (Professor*)p;
            fprintf(stdout,"Starting Professor %d\n", *professor->id);
    }
    buffer = 0;
    sem_post(&workAssignment);
    pthread_exit(0);
}
int main(int argc, char ** argv){
//Semaphore intialization
    buffer = 0;
    if(sem_init(&workAssignment, 0, 1)){
            printf("Could not initialize semaphore.\n");
            exit(1);
    }

    //Creating threads
    pthread_t professor[num_professors];
    Professor *p;
    int ids[num_professors];
    int i;
    p = malloc (sizeof (*p) * num_professors);

    for(i = 0; i < num_professors; ++i){
            ids[i] = i + 1;
            p->id = &ids[i];
            //printf("Id: %d\n", *p->id);
            if(pthread_create(&professor[i], NULL, professorFunc, p) != 0){
                    perror("pthread_create");
                    exit(1);
            }
            //printf("yo I'm here after function now\n");
    }
    for(i = 0; i < num_professors; ++i){
            if(pthread_join(professor[i], NULL) != 0){
                    perror("pthread_join");
                    exit(1);
            }
    }
    free(p);
}

【问题讨论】:

    标签: c memory pthreads semaphore shared


    【解决方案1】:

    这一行:

    if(pthread_create(&professor[i], NULL, professorFunc, p) != 0){
    

    应该是:

    if(pthread_create(&professor[i], NULL, professorFunc, &p[i]) != 0){
    

    【讨论】:

    • 啊,所以在更改后:p-&gt;id = &amp;ids[i];p[i].id = &amp;ids[i]; 它可以工作。所以 malloc'ing p with sizeof(*p) * num_professors 基本上使 p 成为一个包含 num_professors 元素的数组。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-14
    • 2015-05-26
    • 1970-01-01
    • 1970-01-01
    • 2010-10-26
    相关资源
    最近更新 更多