Reputation: 53
lets say i have this code in main:
std::shared_ptr<std::string> command = std::make_shared<std::string>();
std::atomic<bool> done(true);
std::thread videoShow;
while (1) {
std::getline(cin, *command);
std::cout << *command;
if ((*command).find("video") != std::string::npos) {
if ((*command).find("start") != std::string::npos && done) {
videoShow = std::thread(Video::showFrames, command, std::ref(done));
}
}
}
and this code in the function Video::showFrames:
void showFrames(std::shared_ptr<std::string> command, std::atomic<bool>& isDone){
isDone = false;
while (1) {
std::cout << "this is command" << *command;
}
}
why if i write the command "video start" the output is:
this is command video start (first call to std::cout in main)
this is command
this is command ...
why is the call to *command in the 4th line of the function showFrames not working?
Upvotes: 0
Views: 120
Reputation: 9058
This is kind of scary code to me. Your main is sitting their loading strings. Your worker thread is doing a fast-loop.
But the thread start up takes time. So let's say line 2 of your file has your video start string in it. Great. You spawn a thread. And then you immediately go do a fresh getline, trashing the old string you just read, before the thread has a chance to use it.
I'm not sure what you're really trying to do, but I see no reason to use the shared pointer. Just pass the string by value (let it get copied) and be done with it, it seems to me.
Upvotes: 1