Skip to content
Permalink
45e50ceab7
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
62 lines (52 sloc) 1.51 KB
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <thread>
#include <chrono>
#include <windows.h>
#include <mutex>
#include <condition_variable>
using namespace std;
mutex mlock;
condition_variable con;
bool available = false;
string readChar;
void consumer(int input) {
unique_lock<mutex> lck(mlock);
con.wait(lck);
//?
}
void producer(char input) {
unique_lock<mutex> lck(mlock);
readChar += input;
con.notify_all();
}
void thread1(string poem)
{
Sleep(1000); //wait 1 second
cout << poem << endl; //output the current line of the poem
}
int main()
{
ifstream inFile;
vector<string> output;
string line;
int c = 0;
inFile.open("poem.txt"); //open the poem, stored locally
if (!inFile) {
cout << "Unable to open file"; //if the file cannot be opened
exit(1); // terminate with error
}
while (getline(inFile, line)) { //while there are still lines of the poem that can be read
thread t1(thread1, line); //send the current line of the poem to thread1 in order to output
t1.join(); //ensure that the thread has completed
output.push_back(line);
for (int c = 0; c < line.length(); c++) { //for every character in the line .....
thread cons(consumer, line.substr(c, 1)); //produce and consume the Cth character until the line has been processed
thread prod(producer, line.substr(c, 1));
prod.join();
cons.join();
}
}
}