【发布时间】:2019-08-23 11:17:34
【问题描述】:
我有一个在 std::thread 中处理的状态机。该状态机初始化网络连接,处理数据,并在收到特定消息后,需要自行关闭。以这种方式使用 join 会触发“已调用 abort()”异常。这是适合分离线程的情况之一吗?
#include <iostream>
#include <thread>
#include <atomic>
#include <memory>
class ThreadExample
{
public:
ThreadExample()
{
StartThread();
}
void StartThread()
{
//start thread;
run_thread = true;
the_thread = std::thread(&ThreadExample::ThreadFunction, this);
}
void ThreadFunction()
{
while (run_thread)
{
if (correct_message_found)
ShutdownThread();
else
ProcessMessage(); //example code to imitate network processing
//arbitrary wait. not relevant to the problem
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
//read in by some network connection
void ProcessMessage(/*some message data*/)
{
static int counter = 0;
if (counter == 3)
{
correct_message_found = true;
}
else
{
std::cout << "Waiting for the right message\n";
counter++;
}
}
void ShutdownThread()
{
run_thread = false;
if (the_thread.joinable())
the_thread.join();
}
private:
std::thread the_thread;
std::atomic_bool run_thread;
bool correct_message_found = false;
};
int main()
{
auto example = std::make_unique<ThreadExample>();
int data;
std::cin >> data;
}
【问题讨论】:
-
对不起,描述不够清楚。线程如何自行关闭?谁打电话给
join?你会在哪里分离线程?线程的副作用是什么,为什么首先要线程?请务必创建您正在谈论的最小代表性示例,它会更清晰。您想回答的具体问题是什么? -
我会模拟一些东西。
-
只要有人else记得
join线程,你仍然可以随时退出线程(通过从线程主函数返回)。 -
你不能加入一个线程本身。它必须由另一个线程完成。但是,只要不是线程本身破坏了对象,就不会禁止或禁止从析构函数中执行此操作。
-
您的前两句话似乎毫无关联。 “以这种方式使用连接......”以什么方式?调用
join不会使线程终止,它只是让调用线程等待,直到另一个线程完成执行
标签: c++ multithreading join detach