gpt4 book ai didi

c++ - 如何为同一类对象的成员函数保留单独的变量拷贝?

转载 作者:太空狗 更新时间:2023-10-29 20:51:47 24 4
gpt4 key购买 nike

  • 我有一个类对象 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;

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

引用:http://en.cppreference.com/w/cpp/keyword/thread_local

关于c++ - 如何为同一类对象的成员函数保留单独的变量拷贝?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48587069/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com