[英]How can I keep separate variable copy for same class object's member function?
The issue is: when I run both threads, the wr_count value is being shared between both threads. 问题是:当我运行两个线程时,两个线程之间共享wr_count值。
For eg thread_1 runs 8-times and makes the wr_count=8 but when thread_2 starts it makes the wr_count=9 . 例如,thread_1运行8次并使wr_count = 8,但是当thread_2启动时,它使wr_count = 9 。 I want thread_2 to start counting from "1" not from the last value of thread_1.
我希望thread_2从“1”开始计数而不是从thread_1的最后一个值开始计数。
Here is my code: 这是我的代码:
#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;
}
};
This is a perfect job for the thread_local
storage duration, which is a keyword introduced from C++11. 这是
thread_local
存储持续时间的完美工作,这是从C ++ 11引入的关键字 。
thread_local int wr_count;
Essentially, you get a separate static
instance of wr_count
per thread; 实际上,每个线程都会获得一个单独的
wr_count
static
实例; each one is initialised to 0
. 每个都初始化为
0
。
Reference: http://en.cppreference.com/w/cpp/keyword/thread_local 参考: http : //en.cppreference.com/w/cpp/keyword/thread_local
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.