main.cpp

//main.cpp
#include <cstring>
#include <unistd.h>
#include <sys/stat.h>
#include "global.h"

using namespace std;

int  main(int argc, char **argv)

{
  pthread_t *tids;
  int cnt = 0;
  int nProducers;
  int nConsumers; 

    

   //记录当前变量Producers的内容
   void *producerNum = &nProducers;

   //提示输入参数,错误告诉用法
   if (argc != 3)
   {
    cerr << "usage: " << argv[0] << " nProducers nConsumers" << endl;
    return -1;

    }

        //自动把参数argv内容转换成整数

	nProducers = atoi(argv[1]);

	nConsumers = atoi(argv[2]);



	//分配相应的内存空间

       tids = (pthread_t *) malloc((nProducers + nConsumers) * sizeof(pthread_t));

   //用来创建循环链表
   bufferInit();

   //用来打开文件
   fileFd = open("output.res", O_CREAT | O_APPEND | O_TRUNC | O_WRONLY,S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
   if (fileFd == -1)
  {
    perror("open file fialed");
    return -1;
   }

   //用来创建设生产者
  for (int i = 0; i < nProducers; ++i)
    {
       if(pthread_create(&tids[cnt++], NULL, blkProducer, producerNum) == -1)
           perror("producer created  failed");
 }

    //用来创建消费者
    for (int i = 0; i < nConsumers; ++i)
    {
       if(pthread_create(&tids[cnt++], NULL, blkConsumer, producerNum) == -1)
           perror(" consumer created failed");
    }

    //互斥量stdoutMutex上锁
    pthread_mutex_lock(&stdoutMutex);
    cout << "init success!" << endl;
   
 //互斥量解锁
    pthread_mutex_unlock(&stdoutMutex);
	for (int i = 0; i < nProducers; ++i )
	{          
            //pthread_join()函数,以阻塞的方式等待tids[i]线程结束
		pthread_join(tids[i], NULL);
              
  //对互斥量stdoutMutex上所
                pthread_mutex_lock(&stdoutMutex);
		cout << "the producer " << i << " exit" << endl;

                //对互斥量解锁
                pthread_mutex_unlock(&stdoutMutex);
	}
	for (int i = 0; i < nConsumers; ++i )
	{       
                //以等待的方式等待tids[nProducers + i]线程结束
		pthread_join(tids[nProducers + i], NULL);

                //对互斥量stdoutMutex上锁
                pthread_mutex_lock(&stdoutMutex);
		cout << "the consumer " << i << " exit" << endl;

               //对互斥量stdoutMutex解锁

               pthread_mutex_unlock(&stdoutMutex);

	}

    return 0;

}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值