sem_wait(&m); // critical section here sem_post(&m);
信号量实现条件变量
sem_t m; sem_init(&m, 0, 0); sem_wait(&s);//阻塞该线程等待某个线程程执行sem_post(&s);唤醒才能继续往下执行 .....
生产者/消费者
sem_t empty; sem_t full; sem_t mutex;
void *producer(void *arg) { int i; for (i = 0; i < loops; i++) { sem_wait(&empty); // line p1 sem_wait(&mutex); // line p1.5 (MOVED MUTEX HERE...) put(i); // line p2 sem_post(&mutex); // line p2.5 (... AND HERE) sem_post(&full); // line p3 } } void *consumer(void *arg) { int i; for (i = 0; i < loops; i++) { sem_wait(&full); // line c1 sem_wait(&mutex); // line c1.5 (MOVED MUTEX HERE...) int tmp = get(); // line c2 sem_post(&mutex); // line c2.5 (... AND HERE) sem_post(&empty); // line c3 printf("%d\n", tmp); } }
intmain(int argc, char *argv[]) { // ... sem_init(&empty, 0, MAX); // MAX buffers are empty to begin with... sem_init(&full, 0, 0); // ... and 0 are full sem_init(&mutex, 0, 1); // mutex=1 because it is a lock // ... }