簡體   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