这段代码很好地展示了关键部分问题,但我有两个关于代码的问题,
- 如何显示哪个线程被拒绝进入关键部分?
- 线程“A”、“B”、“C”按列出的顺序创建。我怎样才能一次启动它们?
这是代码:
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
void *doSomething1();
void *doSomething2();
void *doSomething3();
sem_t sem;
int main() {
    // initialize semaphore to 2
    sem_init(&sem, 1, 2);
    pthread_t thread1, thread2, thread3;
    pthread_create(&thread1, NULL, &doSomething1, NULL);
    pthread_create(&thread2, NULL, &doSomething2, NULL);
    pthread_create(&thread3, NULL, &doSomething3, NULL);
    pthread_join(thread1, NULL);
    pthread_join(thread2, NULL);
    pthread_join(thread3, NULL);
    return 0;
}
void doSomething(char c) {
    int i, time;
    for (i = 0; i < 3; i++) {
        if (sem_wait(&sem) == 0) {
            // generate random amount of time (< 7 seconds)
            time = (int) ((double) rand() / RAND_MAX * 7 );
            printf("#thread %c GOT-ACCESS to CRITICAL SESSION for %d sec\n", c, time);
            sleep(time);
            printf("\t->thread %c RELEASED CRITICAL SESSION\n",c);
            sem_post(&sem);
        }
    else    
        printf("thread %c FAILED TO ENTER CRITICAL SECTION",c);
    }
}
void *doSomething1() {
    // thread A
    doSomething('A');    return 0;
}
void *doSomething2() {
    // thread B
    doSomething('B');    return 0;
}
void *doSomething3() {
    // thread C
    doSomething('C');    return 0;
}