在C ++ 11中,我创建了一个长期活动的帖子:
class Server
{
public:
void operator() () const {
while(true)
dosomething();
}
~Server()
{
clean();
}
};
// in main
Server s;
std::thread t(s);
t.detach();
我希望在系统终止时使用析构函数添加一些干净的工作。
但是,如果我直接在Server
中添加析构函数,系统启动时将调用clean
。
怎么做?
答案 0 :(得分:0)
在他的书(The C ++ Programming Language,Chapter 42.2.5)中,Bjarne Stroustrup不鼓励使用detach
,如果你不需要,并给出了几个理由。
另见:https://stackoverflow.com/a/22804813/5717589。
在这种情况下的结果是解析器被困在线程中未被执行,cleanup()
不会运行。
我写了下面的代码,看看那里发生了什么:
#include <iostream>
#include <thread>
#include <unistd.h> // for linux usleep
using namespace std;
static bool needed; // tells the server if we need it
class Server {
public:
Server () : id (0){
++id;
cout << "Server " << id << " started. Work status: " << work_done << endl;
}
Server (const Server & rhs) : id (rhs.id){
++id;
cout << "Server " << id << " started by copy. Work status: " << work_done << endl;
}
Server (Server && rhs) : id (rhs.id) {
++id;
cout << "Server " << id << " started by move. Work status: " << work_done << endl;
}
void operator()() {
cout << "Hi! Doing work..." << endl;
work_done = true;
while (needed) {
usleep(300000);
cout << "sleeping... Work status: " << work_done << endl;
}
}
~Server() {
cout << "Server " << id << " stopping. Work status: " << work_done << endl;
if (work_done)
cout << "Cleanup triggered by Server " << id << endl;
}
bool work_done {false};
int id;
};
int main() {
needed = true;
Server s;
// thread t(s);
thread t(std::move(s));
// t.detach();
usleep(1000000);
needed = false;
t.join();
cout << "end" << endl;
}
输出结果为:
Server 1 started. Work status: 0
Server 2 started by move. Work status: 0
Server 3 started by move. Work status: 0
Server 2 stopping. Work status: 0
Hi! Doing work...
sleeping... Work status: 1
sleeping... Work status: 1
sleeping... Work status: 1
sleeping... Work status: 1
Server 3 stopping. Work status: 1
Cleanup triggered by Server 3
end
Server 1 stopping. Work status: 0
关闭t.detach()
并关闭t.join()
后,结果为:
Server 1 started. Work status: 0
Server 2 started by move. Work status: 0
Server 3 started by move. Work status: 0
Server 2 stopping. Work status: 0
Hi! Doing work...
sleeping... Work status: 1
sleeping... Work status: 1
sleeping... Work status: 1
end
Server 1 stopping. Work status: 0
(令我困惑的是一些临时实例,服务器2,它同时显示移动和复制。)