jeudi 24 mars 2016

C: Correctly Implement a Semaphore

I'm attempting to use semaphores for the first time and I'm receiving an implicit declaration warning on if(rand_r(&seed)%2) { and I'm not sure how to go about fixing this problem.

int sum=0;
unsigned int seed;
sem_t sem0;


void* func0(void *param) {
    int tmp;
    int i;
    for(i=0; i<10; i++) {
        sem_wait (&sem0);
        tmp=sum;
        tmp++;
        if(rand_r(&seed)%2) {
            printf("sleeping for 1 sec\n");
            sleep(1);
        } else {
            printf("sleeping for 2 sec\n");
            sleep(2);
        }
        sem_post (&sem0);
        sem_wait (&sem0);
        sum=tmp;
        if(rand_r(&seed)%2) {
            printf("sleeping for 1 sec\n");
            sleep(1);
        } else {
            printf("sleeping for 2 sec\n");
            sleep(2);
        }
        sem_post (&sem0);
    }

    return (void*)0;
}

int main() {
    int i;
    int error;
    pthread_t *tid;
    pthread_attr_t attr;

    seed=(unsigned int)time(NULL);

    if((tid=(pthread_t*)calloc(NR_THREAD, sizeof(pthread_t)))==NULL) {
        fprintf(stderr, "calloc() failed\n");
        exit(1);
    }
    sem_init(&sem0, 0, 1);
    if(sem_init(&sem0, 0, 1)==-1) {
        perror("Failed to sem_init() sem0");
        exit(1);
    }

    pthread_attr_init(&attr);
    for(i=0; i<NR_THREAD; i++) {
        if((error=pthread_create(&tid[i], &attr, func0, 
            (void*)0))) {
            fprintf(stderr, "pthread_create() failed: %d %d\n", 
                i, error);
            tid[i]=pthread_self();
        }
    }

    for(i=0; i<NR_THREAD; i++) {
        if(pthread_equal(pthread_self(), tid[i]))
            continue;

        if((error = pthread_join(tid[i], NULL))) {
            fprintf(stderr, "pthread_join() failed: %d %d\n", 
                i, error);
        }
    }

    printf("Final sum= %d\n", sum);

    free(tid);

    if(sem_destroy(&sem0)==-1) {
        perror("Failed to sem_destroy() sem0");
        exit(2);
    }

    return 0;
}

Output:

bunch of "sleeping for" statements
Final sum=10

This is my first time dabbling in semaphores, so any and all advice is much appreciated!




Aucun commentaire:

Enregistrer un commentaire