Используя рекомендации @DavidSchwartz, я сделал этот код работающим. Пожалуйста, предложите мне лучший способ реализовать это, как будто есть лучшие и более безопасные способы сделать то, что я сделал. Извините за то, что я не получил большинство комментариев и ответов, так как это мой первый код, использующий pthreads и семафор. Поэтому, пожалуйста, потерпите меня:
#include<iostream>
#include<pthread.h>
#include<fstream>
#include<unistd.h>
#include<semaphore.h>
#include<queue>
// define queue size
#define QUEUE_SIZE 5
// declare and initialize semaphore and read/write counter
static sem_t mutex,mutex1;
//static int counter = 0;
// Queue for saving characters
static std::queue<char> charQueue;
// indicator for end of file
static bool endOfFile = false;
// save arrays
static char consumerArray1[100];
static char consumerArray2[100];
void *Producer(void *ptr)
{
int i=0;
std::ifstream input("string.txt");
char temp;
while(input>>temp)
{
sem_wait(&mutex);
charQueue.push(temp);
sem_post(&mutex1);
sem_post(&mutex);
i++;
sleep(6);
}
endOfFile = true;
sem_post(&mutex1);
pthread_exit(NULL);
}
void *Consumer1(void *ptr)
{
int i = 0;
sem_wait(&mutex1);
bool loopCond = endOfFile;
while(!loopCond)
{
if(endOfFile)
{
loopCond = charQueue.empty();
std::cout<<loopCond<<std::endl;
sem_post(&mutex1);
}
sem_wait(&mutex1);
sem_wait(&mutex);
if(!charQueue.empty())
{
consumerArray1[i] = charQueue.front();
charQueue.pop();
i++;
}
if(charQueue.empty()&&endOfFile)
{
sem_post(&mutex);
sem_post(&mutex1);
break;
}
sem_post(&mutex);
sleep(2);
}
consumerArray1[i] = '\0';
pthread_exit(NULL);
}
void *Consumer2(void *ptr)
{
int i = 0;
sem_wait(&mutex1);
bool loopCond = endOfFile;
while(!loopCond)
{
if(endOfFile)
{
loopCond = charQueue.empty();
std::cout<<loopCond<<std::endl;
sem_post(&mutex1);
}
sem_wait(&mutex1);
sem_wait(&mutex);
if(!charQueue.empty())
{
consumerArray2[i] = charQueue.front();
charQueue.pop();
i++;
}
if(charQueue.empty()&& endOfFile)
{
sem_post(&mutex);
sem_post(&mutex1);
break;
}
sem_post(&mutex);
sleep(4);
}
consumerArray2[i] = '\0';
pthread_exit(NULL);
}
int main()
{
pthread_t thread[3];
sem_init(&mutex,0,1);
sem_init(&mutex1,0,1);
pthread_create(&thread[0],NULL,Producer,NULL);
int rc = pthread_create(&thread[1],NULL,Consumer1,NULL);
if(rc)
{
std::cout<<"Thread not created"<<std::endl;
}
pthread_create(&thread[2],NULL,Consumer2,NULL);
pthread_join(thread[0],NULL);pthread_join(thread[1],NULL);pthread_join(thread[2],NULL);
std::cout<<"First array: "<<consumerArray1<<std::endl;
std::cout<<"Second array: "<<consumerArray2<<std::endl;
sem_destroy(&mutex);
sem_destroy(&mutex1);
pthread_exit(NULL);
}