I would like to be able to output information while inputting. For example: Printing a line every second, but also taking user input...
I tried:
#include <iostream>
#include <thread>
#include <string>
#include <unistd.h>
using namespace std;
void foo()
{
while(1)
{
usleep(1000000);
cout << "Cake\n";
}
}
int main()
{
thread t1(foo);
t1.join();
string x;
while(1)
{
cin >> x;
cout << x << "\n";
}
return 0;
}
Which outputs:
Cake
Cake
Cake
And then I start typing:
hiCake
When I would like it to be:
Cake
hi
Where the 'hi' is still in the input
If this isn't possible, is there at least a way for me to pause the outputting while there is text being inputted?
I'm using C++11 on Windows 7 using CygWin for the Unix libraries
MUTEX TESTS
Output loop locked:
#include <iostream>
#include <thread>
#include <string>
#include <unistd.h>
#include <mutex>
using namespace std;
mutex mtx;
void foo()
{
mtx.lock();
while(1)
{
usleep(1000000);
cout << "Cake\n";
}
mtx.unlock();
}
int main()
{
thread t1(foo);
t1.join();
string x;
while(1)
{
cin >> x;
cout << x << "\n";
}
return 0;
}
Input loop locked:
#include <iostream>
#include <thread>
#include <string>
#include <unistd.h>
#include <mutex>
using namespace std;
mutex mtx;
void foo()
{
while(1)
{
usleep(1000000);
cout << "Cake\n";
}
}
int main()
{
thread t1(foo);
t1.join();
string x;
mtx.lock();
while(1)
{
cin >> x;
cout << x << "\n";
}
mtx.unlock();
return 0;
}
Pure output locked:
#include <iostream>
#include <thread>
#include <string>
#include <unistd.h>
#include <mutex>
using namespace std;
mutex mtx;
void foo()
{
while(1)
{
mtx.lock();
usleep(1000000);
cout << "Cake\n";
mtx.unlock();
}
}
int main()
{
thread t1(foo);
t1.join();
string x;
while(1)
{
cin >> x;
cout << x << "\n";
}
return 0;
}
Pure input locked:
#include <iostream>
#include <thread>
#include <string>
#include <unistd.h>
#include <mutex>
using namespace std;
mutex mtx;
void foo()
{
while(1)
{
usleep(1000000);
cout << "Cake\n";
}
}
int main()
{
thread t1(foo);
t1.join();
string x;
while(1)
{
mtx.lock();
cin >> x;
mtx.unlock();
cout << x << "\n";
}
return 0;
}
To save space, I won't paste more code; I did other tests where I made a mutex mtx2
and tried to lock both input (mtx
) and output(mtx2
) (both pure and the loops). I did also try locking both with mtx
(again, both pure and loops)