### 用條件變量（Condition Variable）實現信號量（Semaphore）

struct sem{
int num;

};

void  sem_init(sem_t * semm, int num) 初始化函數，定義資源數。

void sem_wait(sem_t * semm) 獲取資源，獲得資源后，資源數-1，未獲得資源則掛起等待，

void sem_post(sem_t * semm) 釋放資源，資源數+1；

//"semaphore_xx.h"

#ifndef SEMAPHORE_XX_20121008
#define SEMAPHORE_XX_20121008

#include<stdlib.h>
#include<errno.h>
#include<unistd.h>
#include <sys/types.h>
#include <sys/stat.h>

namespace sem_xx{
struct sem{
int num;

};

typedef struct sem sem_t;

void  sem_init(sem_t * semm, int num){
semm->num = num;
}

void sem_wait(sem_t * semm){
while ( semm->num == 0)
semm->num--;
}

void sem_post(sem_t * semm){
/*fuck! Here is a stupid mistake!Just add the num will be ok!!
Otherwise,we will be blocked here！
while ( semm->num == 0)

*/
semm->num++;

}
}
#endif

//"test.cpp"

#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
//#include <semaphore.h>
#include "semaphore_xx.h"

#define NUM 5
int queue[NUM];

using namespace sem_xx;

sem blank_number, product_number;

void *producer(void *arg)
{
int p = 0;
while (1) {
sem_wait(&blank_number);
queue[p] = rand() % 1000 + 1;
printf("Produce %d\n", queue[p]);
sem_post(&product_number);
p = (p+1)%NUM;
sleep(rand()%5);
}
}

void *consumer(void *arg)
{
int c = 0;
while (1) {
sem_wait(&product_number);
printf("Consume %d\n", queue[c]);
queue[c] = 0;
sem_post(&blank_number);
c = (c+1)%NUM;
sleep(rand()%5);
}
}

int main(int argc, char *argv[])
{
sem_init(&blank_number, NUM);
sem_init(&product_number, 0);

return 0;
}