#include <cstdio>
#include <iostream>
#include <fstream>
#include <thread>
using namespace std;
void fwriter(fstream &f) {
f << " write ok"<<endl;
}
int main()
{
fstream f;
f.open("log.txt", fstream::in | fstream::out | fstream::app);
thread th;
th = thread(fwriter, ref(f));
cout<<th.get_id()<<endl;
th.join();
cout<<th.get_id()<<endl;
cout << "OK" << endl;
getchar();
return 0;
}
因此,这里这样的程序是不执行join后的流程。
thread::id of a non-executing thread
之后线程是否释放了所有资源?你需要做点别的th.swap(thread());
吗?
调用之后
join()
,线程对象不再控制线程,就像 when 一样detach
。get_id()
正确返回一个空 id - 虽然这并不意味着线程本身被永久销毁,它只是不会有可见的副作用。调用后,
join()
传递的函数对象保证被执行,即 在您的情况下,写入文件已完成,可以进行另一次写入。不知道何时以及如何删除此函数对象,但在您的情况下,它仅包含引用,何时删除它们并不重要 - 文件对象本身由根线程管理。在更复杂的情况下,您需要考虑到函数对象的析构函数可以在另一个线程中调用(否则将无法实现
detach
),这意味着必须通过引用来捕获资源,以便它们始终被销毁在根线程中,或按值 - 那么它们将在哪个流中被破坏都没有关系(但在这里很有可能在脚上开枪),或通过shared_ptr
,在这种情况下类似于按值捕获。