-
Cristian Lalescu authoredCristian Lalescu authored
lock_free_bool_array.hpp 2.48 KiB
/******************************************************************************
* *
* Copyright 2019 Max Planck Institute for Dynamics and Self-Organization *
* *
* This file is part of TurTLE. *
* *
* TurTLE is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published *
* by the Free Software Foundation, either version 3 of the License, *
* or (at your option) any later version. *
* *
* TurTLE is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with TurTLE. If not, see <http://www.gnu.org/licenses/> *
* *
* Contact: Cristian.Lalescu@ds.mpg.de *
* *
******************************************************************************/
#ifndef LOCK_FREE_BOOL_ARRAY_HPP
#define LOCK_FREE_BOOL_ARRAY_HPP
#include <vector>
#include <memory>
class lock_free_bool_array{
std::vector<std::unique_ptr<long int>> keys;
public:
explicit lock_free_bool_array(const long int inNbKeys = 512){
keys.resize(inNbKeys);
for(std::unique_ptr<long int>& k : keys){
k.reset(new long int(0));
}
}
void lock(const long int inKey){
volatile long int* k = keys[inKey%keys.size()].get();
long int res = 1;
while(res == 1){
res = __sync_val_compare_and_swap(k, 0, res);
}
}
void unlock(const long int inKey){
volatile long int* k = keys[inKey%keys.size()].get();
assert(k && *k);
(*k) = 0;
}
};
#endif