Why the output isn't consistently 1 , when I declared Counter object as thread_local
#include <iostream>
#include <thread>
#define MAX 10
class Counter {
    int c;
    public:
    Counter() : c(0) {}
    void increment() {
        ++c;
    }
    ~Counter() {   
        std::cout << "Thread " << std::this_thread::get_id() << " having counter value " << c << "\n";  
    }
};
thread_local Counter c;
void doWork() {
    c.increment();
}
int main() {
    std::thread t[MAX];
    for ( int i = 0; i < MAX; i++ )
        t[i] = std::thread(doWork);
    for ( int i = 0; i < MAX; i++ )
        t[i].join();    
    return 0;
}
Output :
Thread 2 having counter value 19469616 Thread 3 having counter value 1 Thread 4 having counter value 19464528 Thread 5 having counter value 19464528 Thread 7 having counter value 1 Thread 6 having counter value 1 Thread 8 having counter value 1 Thread 9 having counter value 1 Thread 10 having counter value 1 Thread 11 having counter value 1
Aucun commentaire:
Enregistrer un commentaire