I use the codes below to test detach (in ubuntu18.5, g++7.5):
#include <thread>
#include <fstream>
#include <chrono>
#include <iostream>
using namespace std;
void long_process()
{
ofstream ofs("test.log", ios::app);
ofs<<"long process start" <<endl;
std::this_thread::sleep_for(std::chrono::milliseconds(3*1000)); //wait 3 seconds
ofs<<"long process end" <<endl;
}
int main()
{
ofstream ofs("test.log", ios::app);
ofs << "main start" <<endl;
std::thread th(long_process);
th.detach();
ofs << "main end" <<endl; }
But in the test.log, I only see 3 lines, it seems long_process stopped after detach.
main start
main end
long process start
I think the result of detach should be:
main start
main end
long process start
long process end
If I change detach to join, it works.
main start
long process start
long process end
main end
I don't know why.
Aucun commentaire:
Enregistrer un commentaire