我试图让我的输出
Starting Professor 1
Starting Professor 2
Starting Professor 3
...
但是我从来没有得过#34;开始教授1"当num_professors = 2.我想制作一个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);
}
答案 0 :(得分:1)
这一行:
if(pthread_create(&professor[i], NULL, professorFunc, p) != 0){
应该是:
if(pthread_create(&professor[i], NULL, professorFunc, &p[i]) != 0){