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

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

本文关键字:函数 成员 保留 单独 副本 变量 对象 一类      更新时间:2023-10-16
  • 我有一个类对象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;
}
};

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

thread_local int wr_count;

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

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