如何在 C++ 循环内连续检索和使用变量的更新值

问题描述 投票:0回答:1

在 C++ 中,如何访问和使用在循环内不断修改的变量的更新值,然后通过以线程安全的方式调用另一个函数或方法来返回或利用该值?”

这是我尝试过的示例代码:

#include <iostream>
#include <thread>
#include <atomic>
#include <vector>

class Sample {
private:
    std::atomic<int> total_width; // Use an atomic to make it thread-safe
    std::atomic<int> n; // Use an atomic to make it thread-safe
    std::atomic<bool> stop;
    std::vector<std::string> s;

public:
    Sample() : total_width(0), n(0), stop(false) {}

    void SetSample() {
        while (!stop.load()) {
            n++;
            for (int i = 0; i < s.size(); ++i) {
                if (i == 2) {
                    total_width = 1;
                } else {
                    total_width = 0;
                }
            }
            std::this_thread::sleep_for(std::chrono::milliseconds(100)); // Simulate some work
        }
    }

    void append(const std::string& SSS) {
        s.push_back(SSS);
    }

    int GetTotalWidth() const {
        return total_width.load();
    }

    int GetN() const {
        return n.load();
    }

    void StopUpdating() {
        stop.store(true);
    }
};

int main() {
    Sample sample;

    std::thread updaterThread(&Sample::SetSample, &sample);
    sample.append("s");
    sample.append("s");
    sample.append("s");
    sample.append("s");
    sample.append("s");
    sample.append("s");
    sample.append("s");
    sample.append("s");
    sample.append("s");

    // You can now retrieve the updated total_width in a loop
    for (int i = 0; i < 100; ++i) {
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
        std::cout << "\t" << sample.GetN() << " -> " << "Total Width: " << sample.GetTotalWidth() << std::endl;
    }

    // Stop the updater thread
    sample.StopUpdating();
    updaterThread.join();

    return 0;
}

这段代码的问题在于,似乎声明

if(i==2){...}

不进行计算,当“i”为 2 时,它总是输出 0 而不是 1。

c++ thread-safety
1个回答
0
投票

你的代码基本上根本不是线程安全的,因为 std::vector 不是线程安全的。

至于你问的问题:我不知道你希望完成什么,但你的代码没有时间看到“total_width 1”:大多数时候它是0。

如果你做类似的事情,你实际上可以打印“1”结果

if (i == 2) {
   total_width = 1;
   std::this_thread::sleep_for(std::chrono::milliseconds(1000));
} else {
   total_width = 0;
}

因此您的其他线程有机会实际看到该结果。

这并不会使事情成为线程安全的,它只是解释了为什么你在输出中没有看到total_width 1。或者,通常不会——它可能会发生,但可能性不大。

© www.soinside.com 2019 - 2024. All rights reserved.