繁体   English   中英

如何为同一个类对象的成员函数保留单独的变量副本?

[英]How can I keep separate variable copy for same class object's member function?

  • 我有一个类对象obj1 ,我试图从2个单独的线程调用成员函数sdf_write
  • 在member-function中有一个静态变量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;
    }
};

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

thread_local int wr_count;

实际上,每个线程都会获得一个单独的wr_count static实例; 每个都初始化为0

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM