谢金运 谢金运 - 1 month ago 10
C++ Question

c++ 11 std::thread use ofstream output stuff, but get nothing, why?

What would happen after running these code below?

#include <thread>
#include <chrono>
#include <functional>
#include <fstream>

using namespace std;

void func()
{
std::this_thread::sleep_for(std::chrono::seconds(5));
ofstream outfile("test.txt");
outfile << "hello world" << endl;
outfile.close();
}

void start()
{
std::thread th(std::bind(func));
if (th.joinable())
th.detach();
}

int main()
{
start();
return 0;
}


Result is that "test.txt" file will not be created in the disk. why?

In addition, are there problems if I use the heap data which new in start() function in the func()? The os will delete it when the main thread return but the child thread still running?

Tas Tas
Answer

As @Brandon has pointed out in the comments, your thread very likely doesn't get a chance to run. main() calls start() which constructs the thread, then returns back to main() which then exits. Even if your thread got a chance to run in that time, you put a 5s sleep in there.

You need to wait for your thread to finish before terminating the program. You can use std::thread::join for this:

void start()
{
    std::thread th(std::bind(func));
    // if the thread was successfully created
    if (th.joinable())
        // wait for it to finish
        th.join();
}

You could also consider std::condition_variable if you didn't need to wait entirely on your thread, and your thread could alert you when some of its work is done.