Homerdough
Homerdough

Reputation: 173

Getting wrong value for ID in pthreads

I'm trying to get my output to be

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

but I never get "Starting Professor 1" when num_professors = 2. I thought making an array of ids would save the whole passing in of the address of id, but apparently not. There's about 70 other things I have to do for this project and having a roadblock on this simple thing (that probably takes a few seconds to fix) is quite frustrating to say the least. Thanks is greatly appreciated

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

Upvotes: 0

Views: 49

Answers (1)

JS1
JS1

Reputation: 4767

This line:

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

should be:

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

Upvotes: 1

Related Questions