假设银行三个窗口,十个人办业务
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
int COUNT = 3 ;//窗口数
pthread_mutex_t mutex;
void* th(void* arg)
{
while(1)
{
pthread_mutex_lock(&mutex);
if(COUNT>0)
{
COUNT--;
pthread_mutex_unlock(&mutex);
printf("get win...\n");//获得窗口(办业务)
sleep(rand()%5);//办理业务时间
printf("release win...\n");//释放窗口
pthread_mutex_lock(&mutex);
COUNT++;
pthread_mutex_unlock(&mutex);
break;
}
else
{
pthread_mutex_unlock(&mutex);
}
}
return NULL;
}
int main(int argc, const char *argv[])
{
pthread_t tid[10]={0};
int i = 0;
pthread_mutex_init(&mutex,NULL);
for(i = 0 ;i<10;i++)
{
pthread_create(&tid[i],NULL,th,NULL);
}
for(i = 0 ;i<10;i++)
{
pthread_join(tid[i],NULL);
}
pthread_mutex_destroy(&mutex);
return 0;
}