在 pthreads 中获取错误的 ID 值

Getting wrong value for ID in pthreads

我正在努力使我的输出成为

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

这一行:

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

应该是:

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