//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;
}