Thursday, February 15, 2018

Compare and Swap(CAS) implementation for counter shared data in C++

 implementation in simple increase counter:

#include <iostream>
#include <thread>
#include <unistd.h>
#include <atomic>

std::atomic<int> count(0);
std::mutex n_mutux;

void increase_counter()
{
    int old_value = count.load(); ;
    while (!count.compare_exchange_weak(old_value, old_value +1))
    {
    }



}


int main() {
    unsigned int n = std::thread::hardware_concurrency();
    std::cout << n << " concurrent threads are supported.\n";
    int thread_num =10;
    std::thread t[thread_num];
    for(int i=0;i<thread_num;i++)
    {
        t[i]=std::thread((increase_counter));
    }

    for(int i=0;i<thread_num;i++)
    {
        t[i].join();
    }
   std::cout<<count;
}





implementation with vector and structure:



//// Created by Laxmi Kadariya on 2/14/18.//
#include <iostream>
#include <vector>
#include <thread>
#include <atomic>



std::atomic<int> count(0);
struct Counter {
    int value;

    Counter() : value(0){}

    void increment(){
        int old_value = count.load(); ;
        while (!count.compare_exchange_weak(old_value, old_value +1))
        {
        }
//        ++value;
    }
};

int main(){
    Counter counter;

    std::vector<std::thread> threads;
    for(int i = 0; i < 10; ++i){
        threads.push_back(std::thread([&counter](){
            for(int i = 0; i < 1000; ++i){
                counter.increment();
            }
        }));
    }

    for(auto& thread : threads){
        thread.join();
    }

    std::cout << count << std::endl;
//    std::cout << counter.value << std::endl;

    return 0;
}

No comments:

Post a Comment