![](/img/trans.png)
[英]How can I obtain a member function pointer to the copy constructor of a class?
[英]How can I keep separate variable copy for same class object's member function?
問題是:當我運行兩個線程時,兩個線程之間共享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
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.