用线程和互斥锁实现的简单的卖票系统

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

int ticket = 100;   // 票

// 互斥锁
pthread_mutex_t mutex;

// 卖票线程
void *sale_ticket(void *v)
{
	int window = (int)v;
	
	printf ("窗口 %d  开始卖票
", window);
	
	while (1)
	{
		int time = rand() % 100 + 1;
		usleep(time*10000);
		
		// 卖票前要先抢锁
		pthread_mutex_lock(&mutex);
		
		if (ticket == 0)
		{
			pthread_mutex_unlock(&mutex);
			break;
		}
		
		printf ("窗口 %d  卖票了一张票 : %d
", window, ticket);
		ticket--;
		
		pthread_mutex_unlock(&mutex);
	}
}

int main()
{
	srand ((unsigned int)time(NULL));
	
	// 初始化互斥锁
	pthread_mutex_init(&mutex, NULL);
	
	// 创建卖票的线程
	int i = 0;
	for (i = 1; i < 5; i++)
	{
		pthread_t therad_id;
		pthread_create(&therad_id, NULL, sale_ticket, (void*)i);
		pthread_detach(therad_id);
	}
	
	
	pthread_exit(NULL);
	
	// 销毁互斥锁
	pthread_mutex_destroy(&mutex);
	return 0;
}

昨天是用共享内存和信号量实现的,今天通过多线程和互斥锁实现,线程相比较于进程,进程所消耗的CPU资源多,进程间通信复杂,线程通信简单方便。
经验分享 程序员 微信小程序 职场和发展