类成员变量的 C++ 线程访问问题

标签 c++ multithreading

在使用线程一段时间后,我遇到了这样一种情况:我需要一个线程永远运行,直到一个函数(或任何类型的事件)被调用。为此,我创建了一个 bool 值来控制线程执行的函数内的 while 循环,但我很快注意到在线程开始运行后外部变量不会更新,导致线程在被要求时永远不会停止.

下面是一些简单的代码来表示这个问题:

#include <cstdio>
#include <thread>
#include <chrono>

class A {
public:
    A();

    void startThread();
    void endThread();
private:
    void threadCall();
    bool active;
};

int main() {
    A threadThing;
    threadThing.startThread();
    printf("[M] Thread Created\n");
    std::this_thread::sleep_for(std::chrono::seconds(5));
    threadThing.endThread();
    printf("[M] Thread Killed\n");
    std::this_thread::sleep_for(std::chrono::seconds(5));

    return 0;
}

A::A() {
    active = false;
}

void A::startThread() {
    active = true;
    std::thread AThread(&A::threadCall, *this);
    AThread.detach();
}

void A::endThread() {
    active = false;
}

void A::threadCall() {
    printf("[T] Thread Started\n");
    while (active) {
        std::this_thread::sleep_for(std::chrono::seconds(2));
    }
    printf("[T] Thread Ended\n");
}

预期的结果是 main 函数启动线程,线程说它开始了,然后 4 秒后线程被杀死,线程说它结束,而实际上线程永远不会说它结束。有没有办法让线程访问“事件”变量,或者我解决这个问题的方法完全不正确? (旁注,我确实尝试自己解决这个问题,但只有本地线程存储之类的东西,它似乎只用于线程内部的存储,不能访问外部,但我可能是错的)

最佳答案

问题出在 std::thread 的构造函数上, 它默认复制/移动。

std::thread AThread(&A::threadCall, *this);

这会将对象复制到新线程中,因此检查 active新对象中的变量无效。

您可以删除 *

std::thread AThread(&A::threadCall, this);

你将对象指针传递给新线程,它会调用这样的方法(*this).threadCall() .

编辑:正如评论所说,这不能保证线程安全,您需要使用 std::atomic<bool>为了安全。

关于类成员变量的 C++ 线程访问问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20768750/

相关文章:

ios - 从后台线程在 UINavigationItem 上显示 UISearchController

java - jconsole 中的类溢出

c++ - 删除内存错误

c++ - 用于 C++ 分析的 Very sleepy 和 Callgrind 之间的区别

c++ - unique_ptr 创建说明

.net - 当前逻辑线程增加/线程堆栈泄漏

java - 如何让我的程序等待特定线程并且不影响我的 GUI 的交互性?

c++ - c++中有没有像java一样的timer和timertask之类的东西?

c++ - 使用 SourceTree 克隆 GitHub 上的公共(public)存储库

Java并发hashMap检索