【问题标题】:Guarded thread C++受保护的线程 C++
【发布时间】:2023-03-10 03:34:01
【问题描述】:

我正在尝试创建“guarded_thread”,但收到错误消息“operator=”是“std::__1::thread”的私有成员。这是我的代码:

struct guarded_thread : std::thread{
    using std::thread::thread;
    using std::thread::operator=;
    ~guarded_thread(){if(joinable())join();}
};

一个函数完成了这项工作,但我想知道如何以另一种方式创建它

void Guarded_thread(std::thread &Thread){
    if (Thread.joinable()) {
        Thread.join();
    }
}

【问题讨论】:

  • 请出示minimal reproducible example 并解释您的代码应该做什么。这个错误不是很容易解释吗?您正在尝试使用 std::thread 上的私有赋值运算符
  • 请注意,C++20 有 std::jthread,并且(公开)从 std 类型继承并不总是最好的主意。
  • std::thread 不能被复制,因此任何类都不能从它继承。但是你可以为你的类创建一个简单的std::thread 成员变量,而不是继承。
  • 代码也没有考虑到线程可以无限期地运行并且在调用析构函数时运行。 jthread被要求从析构函数中停止,这是jthread的一个特性。

标签: c++ multithreading stdthread


【解决方案1】:

std::threads 析构函数不是虚拟的。因此,您将无法多态地使用您的guarded_thread,并且与使线程成为成员相比,继承几乎没有好处。 std::thread 不能被复制,这基本上就是错误所说的,所以guarded_thread 也不能被复制。不过,它可以移动:

#include <thread>
#include <iostream>

struct guarded_thread {
    std::thread t;
    ~guarded_thread() {
        if(t.joinable()) {
            t.join();
        }
    }
};

void foo(guarded_thread&& t) {}

int main() {
    foo(guarded_thread{ std::thread{ [](){ std::cout << "hello world"; }}});
}

Live Demo

PS:std::thread 没有加入其析构函数对许多人来说是一个惊喜,而且可能也是由引入的 C++20 std::jthread 驱动的。正如 Swift 在评论中指出的那样,std::jthreads 析构函数在加入线程之前也是 request_stop()s 线程,而当线程无限运行时,guarded_thread 将永远阻塞。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-05
    • 1970-01-01
    • 2020-11-24
    • 1970-01-01
    • 2011-06-01
    • 2012-04-26
    • 2015-09-08
    • 2022-01-24
    相关资源
    最近更新 更多