互斥锁

#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <string.h>


int tickets = 100;
pthread_mutex_t mutex;


void delay()
{
int k1 = rand()%10000+1;

while (k1)
{
int k2 = rand()%10000+1;;
while(k2)
{
k2--;
}
k1--;
}
}


void * sale_a(void *arg)
{
int current_tickets;
while(1)
{
pthread_mutex_lock(&mutex);
current_tickets = tickets;
if (current_tickets <= 0)
{
pthread_mutex_unlock(&mutex);
break;
}
printf ("sale_a has sold a ticket: %d\n", current_tickets);
delay();
current_tickets--;
tickets = current_tickets;

pthread_mutex_unlock(&mutex);
}
}


void *sale_b(void * arg)
{
int current_tickets;
while(1)
{
pthread_mutex_lock(&mutex);
current_tickets = tickets;
if (current_tickets <= 0)
{
pthread_mutex_unlock(&mutex);
break;
}
printf ("sale_b has sold a ticket: %d\n", current_tickets);
delay();
current_tickets--;
tickets = current_tickets;
pthread_mutex_unlock(&mutex);
}
}


int main()
{
pthread_t tid1, tid2;
int ret;

srand((unsigned int)time(NULL));

pthread_mutex_init(&mutex, NULL);

ret = pthread_create(&tid1, NULL, sale_a, NULL);
if (ret != 0)
{
printf ("create sale_a thread fail: %s", strerror(ret));
return -1;
}

ret = pthread_create(&tid2, NULL, sale_b, NULL);
if (ret != 0)
{
printf ("create sale_a thread fail: %s", strerror(ret));
return -1;
}

ret = pthread_join(tid1, NULL);
if (ret != 0)
{
printf("wait thread terminates fail:%s", strerror(ret));
return -1;
}

ret = pthread_join(tid2, NULL);
if (ret != 0)
{
printf("wait thread terminates fail:%s", strerror(ret));
return -1;
}
pthread_mutex_destroy(&mutex);
return 0;
}

版权声明:本文为qq_36708941原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。