多线程的创建与结束-小例子火车票的售卖

先记录下用到的变量以及函数

  1. phtread_t :一种新的数据类型,其定义是 typedef unsigned long int pthread_t

  2. pthread_create:线程创建函数,其原型是 int pthread_create(phtread_t * thread,const phtread_arr_t* arr,void* (*start_routine)(void*),void* arg);第一个参数是指向线程标识符的指针,第二个参数是用来设置线程属性,第三个参数是线程运行函数的起始地址,最后一个参数是函数运行的参数

  3. pthread_join 一般是主线程来调用,用来等待子线程退出,因为是等待,所以阻塞的,一般主线程会依次添加所有它创建的子线程   

      接下来是一个用多线程售卖车票的例子

#include<stdio.h>
#include <pthread.h>
#include <windows.h>
#pragma comment(lib, "pthreadVC2.lib")

/*模拟火车售票*/
int total_ticket_num = 20;
pthread_mutex_t mutex_x = PTHREAD_MUTEX_INITIALIZER;
void* sell_ticket(void* arg)
{
	for (int i = 0; i < 20; i++)
	{
		pthread_mutex_lock(&mutex_x);
		if (total_ticket_num > 0)
		{
			Sleep(100);
			int* id = static_cast<int *>(arg);
			printf("thread %d:", *id);
			printf("sell the %dth ticket\n",20 - total_ticket_num + 1);
			total_ticket_num--;
		}
		pthread_mutex_unlock(&mutex_x);
	}
	return 0;
}

int main()
{
	int iRet;
	pthread_t tids[4];
	int i = 0;
	int id[4] = { 0,1,2,3 };
	for (int i = 0; i < 4; i++)
	{
		switch (i)
		{
		case 0:
			iRet = pthread_create(&tids[i], NULL, &sell_ticket, &(id[0]));
			break;
		case 1:
			iRet = pthread_create(&tids[i], NULL, &sell_ticket, &(id[1]));
			break;
		case 2:
			iRet = pthread_create(&tids[i], NULL, &sell_ticket, &(id[2]));
			break;
		case 3:
			iRet = pthread_create(&tids[i], NULL, &sell_ticket, &(id[3]));
			break;
		}
		if (iRet)
		{
			printf("pthread_create error,iRet=%d\n", iRet);
			return iRet;
		}
	}
	Sleep(20);
	void* retval;
	for (int i = 0; i < 4; i++)
	{
		iRet = pthread_join(tids[i], &retval);
		if (iRet)
		{
			printf("tid=%d join error,Ret=%d\n", tids[i],iRet);
			return iRet;
		}
		printf("retval=%ld\n", (long*)retval);
	}
	return 0;
}
/*模拟火车售票*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值