【问题标题】:How can I keep separate variable copy for same class object's member function?如何为同一个类对象的成员函数保留单独的变量副本?
【发布时间】:2018-02-02 16:34:50
【问题描述】:
  • 我有一个类对象 obj1,我正在尝试从 2 个单独的线程调用成员函数 sdf_write
  • 成员函数内部有一个静态变量wr_count

问题是:当我运行两个线程时,两个线程之间共享 wr_count 值。

例如thread_1 运行 8 次并生成 wr_count=8,但当 thread_2 启动时,它会生成 wr_count=9。我希望 thread_2 从“1”开始计数,而不是从 thread_1 的最后一个值开始计数。

这是我的代码:

#include <iostream>
#include <stdio.h>
#include <thread>
#include "sdf_func.hpp"
#include <vector>
using namespace std;
int main() {
    sdf obj1;
    std::thread t1([&obj1](){
        for (int i=0; i<30; i++) {
        while (!obj1.sdf_write(10));
        };
    });
    t1.detach();
    std::thread t2([&obj1](){
        for (int i=0; i<30; i++) {
        while (!obj1.sdf_write(10));
        };
    });
    t2.join();

    cout << "done: " << obj1.done << endl;

    // cout << "done: " << obj2.done << endl;

    // cout << "wr_count: " << obj1.wr_count << endl;
    return 0;   
}

// This is sdf_func/////////////////
#include <iostream>
#include <stdio.h>
#include <thread>
#include <mutex>
using namespace std;
class sdf {
    public:
    int done;
    std::mutex mutex;
    sdf() : done(0){};
    void increment() {
        std::lock_guard<std::mutex> guard(mutex);
        ++done;
    }
    bool sdf_write (auto size) {
        static int wr_count = 0;
        if (wr_count == size) {
            wr_count = 0;
            increment();
            //cout << "done : " << done;
            return false;
        }
        wr_count++;
        cout << wr_count << "--" << std::this_thread::get_id() << endl;
        return true;
    }
};

【问题讨论】:

    标签: c++ multithreading


    【解决方案1】:

    对于thread_local 存储持续时间,这是一个完美的工作,这是一个从 C++11 引入的关键字

    thread_local int wr_count;

    基本上,每个线程都有一个单独的static 实例wr_count;每个都初始化为0

    参考:http://en.cppreference.com/w/cpp/keyword/thread_local

    【讨论】:

    • 谢谢。那很完美。事实证明,我无法在 10 分钟内接受解决方案:D StackExchange。
    猜你喜欢
    • 2011-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多