C++ 从Poco::HTTPServer启动线程

C++ 从Poco::HTTPServer启动线程,c++,multithreading,thread-safety,poco-libraries,C++,Multithreading,Thread Safety,Poco Libraries,我在从Poco::HTTPServer启动线程时遇到了一个奇怪的行为 以下是我得到的: class Worker : public Poco::Runnable { public: Worker(std::string request): _request(request) {}; void run(); std::string GetResult(); private: std::string _request; }; void Worker::run() {

我在从Poco::HTTPServer启动线程时遇到了一个奇怪的行为

以下是我得到的:

class Worker : public Poco::Runnable {
public:
    Worker(std::string request): _request(request) {};
    void run();
    std::string GetResult();
private:
    std::string _request;
};

void Worker::run() {
    // do something with _request;
}

class RequestHandler : public HTTPRequestHandler {
public:
  virtual void handleRequest(HTTPServerRequest &req, HTTPServerResponse &resp) {

    std::string request(static_cast<stringstream const&>(stringstream() << req.stream().rdbuf()).str());

    Poco::Thread thread;
    Worker worker(request);

    std::string response = "";

    thread.start(worker);

    // parsing content of the request to detect if request is async or sync

    if(async) {
    // make dummy response 
        response = "your request queued";
    } else { // if sync
        thread.join();
        response = worker.GetResult();
    }
    ostream& out = resp.send();
    out << response;
    out.flush();
  }

private:
};

我做错了什么?

得到segfault的原因是,当
async
为true时,线程未联接<代码>工作线程将在线程之前被销毁,此时
run()
是否已完成是一个偶然的问题(请记住,它在单独的执行线程中运行)。访问已销毁对象的状态会导致未定义的行为

如果交换
Thread
Worker
的声明,
Thread
将首先被销毁,但具体发生什么(最终肯定是一件坏事)取决于
Worker::run()
是否已经开始执行

因此,join(或其他形式的同步)是保证有序执行和清理的唯一方法。在任何其他场景中,您都有可能发现自己处于已销毁的
Worker
对象的成员函数中

Program received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0x7ffff2e4c700 (LWP 13986)]
0x0000000000000000 in ?? ()
(gdb) bt
#0  0x0000000000000000 in ?? ()
#1  0x00007ffff7a3f76e in Poco::ThreadImpl::runnableEntry (pThread=0x7ffff464e930) at /home/uzurik/libs/poco-PostgreSQL/Foundation/src/Thread_POSIX.cpp:436
#2  0x00007ffff66c26aa in start_thread (arg=0x7ffff2e4c700) at pthread_create.c:333
#3  0x00007ffff69dfeed in clone () at ../sysdeps/unix/sysv/linux/x86_64/clone.S:109