My program, which is executed from the command line, looks like this (execute command declared somewhere else):
int commandHandler::handleRequest(...)
{
bool cmdresult = execute(output);
if cmdresult
{
std::cout << output << std::endl;
}
}
The problem:
If you break the ongoing output to cout with ^C, another call to the program will crash at the output to cout, since "cout is locked but the owner is dead".
How do I prevent this in the easiest way? Are there any methods to check if cout is locked before trying to redirect output to that stream, and in that case, unlock it?
If I do a testprogram like this:
int main(void)
{
std::string output = "Superlongstringwouldbeprinted here... ";
for(int i=0;i<40000;i++)
{
output.append("Superlongstringwouldbeprinted here... ");
}
std::cout << output << std::endl;
}
in the "standard" environment, the output is breakable with ^C and I am able to run the program again with output to std::cout. That is, it seems like the implementation of direction to std::cout is flawed in the real time OS I am writing code for?
If you are with C++11, you may use
std::mutex::lock()
std::mutex::try_lock()
std::mutex::unlock()
functions.
However, you are not so lucky, you may use platform/library dependent codes
In Linux you can use POSIX mutex.
Another good idea to use scoped locks.
Related
I have an application in which I perform costly calculations in parallel worker threads. For simplicity, I write results to stdout directly from these threads.
This worked fine until I changed a few things in an attempt to make the code run faster. First, I replaced std::endl with "\n" to prevent a flushing after every line. And I added the following lines to the init part of my main program:
std::cin.tie(nullptr);
std::ios_base::sync_with_stdio(false);
The basic structure of the worker thread code looks like this:
while(true) {
// get data from job queue, protected by unique_lock on std::mutex
// process the data
// print results
{
std::lock_guard<std::mutex> lk(outputMutex_);
std::cout << "print many results" << "\n"; // was originally std::endl
}
}
Since this "optimization", the output of the workers occasionally "mixes". i.e. the mutex does not serve its intended purpose.
Why is this happening? My understanding is that there is just a single stdout stream buffer, and that the data arrives in the corresponding buffer in sequence, even if the output is not flushed from this buffer before releasing the mutex. But that does not seem to be the case...
(I realize that maybe it would be nicer to have the output generated in a separate thread, but then I'd need to pass back these results using another queue, which did not seem necessary here)
Update: Maybe my post was not clear enough. I do not care about the sequence of the results. The problem is that (for the example above) instead of this:
print many results
print many results
print many results
I sometimes get:
print many print many results
results
print many results
And the outputMutex_ is a static member that is shared by all worker threads.
you are accessing cout by multiple threads. The access to its queue is protected by the mutex, but it needs to be flushed. That doesn't happen automatically (always at least :) )
std::endl flushes cout, '\n' doesn't
or, you can tell cout to flush, with std::flush:
https://en.cppreference.com/w/cpp/io/manip/flush
try:
while(true) {
// get data from job queue, protected by unique_lock on std::mutex
// process the data
// print results
{
std::lock_guard<std::mutex> lk(outputMutex_);
std::cout << "print many results" << "\n"; // not flushed
std::cout << std::flush; // flushed!
std::cout << "print something else" << std::endl; // flushed!
}
}
more on:
https://stackoverflow.com/a/22026764/13735754
I have a multithreaded program in which on thread waits for input through a terminal and the other will get data from the socket. Is there any way to abort first threads cin/scanf to print in console data from second thread.
I think to kill the first thread, print data from second thread then run first thread again. But I'm looking for a better method, something like abort cin then reawoke it.
void thread1(){
cin>>string;
doSomething();
}
void thread2(){
cout<<getSomeData();
}
In usual case, it won't print data till something would be entered from keyboard.
[EDIT]
I found a particular solution, like if it doesn't get input it will interrupt, everything was done in C style.
In any case if you are interested check "Head First C" book, section "Interprocess Communication: It's good to talk".
I know it's bit too late. After a while I was supposed to make cpp multithreaded application again and had the same problem. This time it was done with implementing non blocking input with stdio`s getch() and I think it fits to be the best solution.
I don't know if the following solution is standard enough, but it works on both my Fedora Linux (GCC 10.3) & Windows 10 (MSVC 16.11)
#include <iostream>
#include <csignal>
int main()
{
std::signal(SIGINT, [] (int s)
{
std::signal(s, SIG_DFL);
std::fclose(stdin);
std::cin.setstate(std::ios::badbit); // To differenciate from EOF input
});
std::string input;
std::cout << "Input CTRL+C or EOF now!" << std::endl;
std::getline(std::cin, input);
std::cout << (std::cin.bad() ? "\rinterrupted" : "eof") << std::endl;
}
Don't ask me how to reuse cin from that state now.
I often use cout for debugging purpose in many different places in my code, and then I get frustrated and comment all of them manually.
Is there a way to suppress cout output in the runtime?
And more importantly, let's say I want to suppress all cout outputs, but I still want to see 1 specific output (let's say the final output of the program) in the terminal.
Is it possible to use an ""other way"" of printing to the terminal for showing the program output, and then when suppressing cout still see things that are printed using this ""other way""?
Sure, you can (example here):
int main() {
std::cout << "First message" << std::endl;
std::cout.setstate(std::ios_base::failbit);
std::cout << "Second message" << std::endl;
std::cout.clear();
std::cout << "Last message" << std::endl;
return 0;
}
Outputs:
First message
Last message
This is because putting the stream in fail state will make it silently discard any output, until the failbit is cleared.
To supress output, you can disconnect the underlying buffer from cout.
#include <iostream>
using namespace std;
int main(){
// get underlying buffer
streambuf* orig_buf = cout.rdbuf();
// set null
cout.rdbuf(NULL);
cout << "this will not be displayed." << endl;
// restore buffer
cout.rdbuf(orig_buf);
cout << "this will be dispalyed." << endl;
return 0;
}
Don't use cout for debugging purposes, but define a different object (or function, or macro) that calls through to it, then you can disable that function or macro in one single place.
You can user cerr - standard output stream for errors for your debug purposes.
Also, there is clog - standard output stream for logging.
Typically, they both behave like a cout.
Example:
cerr << 74 << endl;
Details: http://www.cplusplus.com/reference/iostream/cerr/
http://www.cplusplus.com/reference/iostream/clog/
If you include files which involve cout you may want to write the code at the start (outside of main), which can be done like this:
struct Clearer {
Clearer() { std::cout.setstate(std::ios::failbit); }
} output_clearer;
It seems you print debug messages. You could use TRACE within Visual C++/MFC or you just might want to create a Debug() function which takes care of it. You can implement it to turn on only if a distinct flag is set. A lot of programs use a command line parameter called verbose or -v for instance, to control the behavior of their log and debug messages.
This question was inspired by that one.
I've understood how to execute utils from C or C++ code. But how can we get result from some command, that doesn't just printing the result, but enters some interactive mode and works until we press Ctrl+zor something like this? The example of such a command is top.
Usually you don't. You launch the command with options that makes them non interactive.
Technically you could get information from an interactive terminal interface, but you will have a hard time doing it, because in order for the interface to be human like, terminal capabilities are often used (termcaps, ncurses..) which basically works by outputting special characters, so you 'll have to dodge these characters by knowing what is expected when, so except if the interface is quite simple and static (actually even in this case) it's gonna be a pain.
Some applications (such as "dialog") can work interactively and write their final result to a different output stream. In the case of dialog, that is done using stderr (by default). If you have control over the application, you can provide for doing something like that, for passing back information to the calling application.
You simply can access stdin, stdout and stderr. Before you fork create the pipes as needed and fork and after that call execv or any other variant.
An example can be found here:
https://jineshkj.wordpress.com/2006/12/22/how-to-capture-stdin-stdout-and-stderr-of-child-program/
There is also a common used library to capture the output of a child program and react with some new actions on found items. This library was first written for tcl but can also be used for c and c++.
http://expect.sourceforge.net/
With some glue code around the expect lib your source can look like this:
int main()
{
Tcl_Interp *interp = Tcl_CreateInterp();
Expect_Init(interp);
// read from file
int lfd = open( "test.txt", O_RDONLY );
int fd = exp_spawnfd(lfd);
// or read from application
int fd ? exp_spawn("top","top", (char*)0)));
bool cont= true;
Expections set1 =
{
{ exp_glob, "YYY", []( Expection& exp)->void { cout << "found: YYY" << endl; }},
{ exp_regexp, "XXX ([0-9]+)", []( Expection& exp)->void { cout << "found: XXX" << exp.GetResult(1) << endl;}},
{ exp_glob, "END", [&cont]( Expection& exp)->void { cout << "EOF" << endl; cont = false; }}
};
int cnt = 0;
do
{
cout << "Run " << cnt << endl;
cnt++;
Expect ( fd, set1, 2 );
} while ( cont );
cout << "Finish" << endl;
return 0;
}
i am running 2 threads and the text i display first is displayed after the execution of thread
string thread(string url)
{
mutex.lock();
//some function goes here
mutex.unlock();
}
int main()
{
cout<<"asd";
boost::thread t1(boost::bind(&thread));
boost::thread t2(boost::bind(&thread));
t1.join();
t2.join();
}
in the main program i have just displayed an text asd this displayed always after the execution of the thread ..
std::cout << "asd" << std::flush;
Since cout is buffered, data put to it may not appear immediately on the console (or wherever it may be redirected to). Thus, try flushing the output stream within the thread. E.g.
cout << "asd" << endl;
I can't comment on your original post (not enough posts yet); on a tangential note, consider using scoped_lock (if you're not already!), safer than explicit lock/unlock calls...
also one word of caution, flush is expensive, call only when necessary.