无法正确地将struct传递给pthread_create函数

时间:2015-03-16 20:39:19

标签: pthreads

我试图将一个教授结构传递给我的教授函数,但我无法正确地将其中存储的信息传递给该函数。我怀疑它与我的malloc& d p有什么关系,但我认为在它完成后可以解决这个问题。当我尝试打印* professor-> id时,我得到一个段错误,因为显然它决定将p读作内存位置0x0,即使它不在主

typedef struct{
    int *id;
    int *assignings;
    int *min_wait;
    int *max_wait;
    int *min_assignments;
    int *max_assignments;
    int *min_hrs;
    int *max_hrs;
} Professor;

Professor* makeProfessor(){
    Professor *professor = malloc(sizeof *professor);
    return professor;
}

void * professorFunc(void *p){
    Professor *professor = (Professor*)p;
    fprintf(stdout,"Starting Professor %d\n", *professor->id);
    pthread_exit(0);
}

int main(int argc, char **argv){
//Creating threads
    pthread_t professor[num_professors];
    Professor *p;
    int i;
    int id;
    for(i = 0; i < num_professors; ++i){
            id = i + 1;
            p = malloc (sizeof *p);
            p->id = &id;
            if(pthread_create(&professor[i], NULL, professorFunc, (void*)p) != 0){
                    perror("pthread_create");
                    exit(1);
            }
            free(p);
    }
    for(i = 0; i < num_professors; ++i){
            if(pthread_join(professor[i], NULL) != 0){
                    perror("pthread_join");
                    exit(1);
            }
    }

1 个答案:

答案 0 :(得分:0)

您正在分配教授结构数组,并在您的线程有机会对其进行操作之前立即释放它们。实现这一点的更好方法是分配整个数组,处理它们,然后释放内存,一旦你知道线程已经退出(例如下面的例子)。

pthread_t professor[num_professors];
Professor *p;
int i;
int id;
p = malloc (sizeof(*p) * num_professors);
for(i = 0; i < num_professors; ++i){
        id = i + 1;
        p->id = &id;
        if(pthread_create(&professor[i], NULL, professorFunc, (void*)p) != 0){
                perror("pthread_create");
                exit(1);
        }
}
for(i = 0; i < num_professors; ++i){
        if(pthread_join(professor[i], NULL) != 0){
                perror("pthread_join");
                exit(1);
        }
}
free(p);