A thread where it prints values infinitely to console and a main thread which is taking user input from the console, but the input values are being mixed with the output of that thread.
Did give me a hint on how to move further but I was not able to come up with a solution of my own(as I am new to c++).
using namespace std;
mutex mtx;
void foo()
{
while (1)
{
usleep(1000000);
cout << "Cake\n";
}
}
int main()
{
mtx.lock();
thread t1(foo);
string x;
while (true)
{
cin >> x;
edit//fflush(stdin);
cout << x << "\n";
}
t1.join();
mtx.unlock();
return 0;
}
edit 1:
OK to be more precise what i really want is,
IN terminal(presently)
output:cake (which prints every second)
output:cake
output:cake
output:cake
input:hi
output:hicake (still yet to give the enter it echo's the input to console)
output:cake
what i actually want in terminal is input being independent of output
output:cake
output:cake
output:cake
input:hi
output:cake
output:cake
input:hi(waiting still for enter)
//and when enter is pressed it should print to the console
output:hi
output:cake
NOTE: disabling echo didn't help.
Edit 2: The answer posted by me has data processing where the concurrent operation stops on the given commands.
fflush(stdin);is undefined behaviour and makes no sense. Never do that. A mutex that is only used in one thread makes no sense. You need to lock the mutex around each access to your resource in every thread.