Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #pragma once
- #include <iostream>
- #include <atomic.hpp>
- #include <support.hpp>
- namespace tpcc {
- namespace solutions {
- class PetersonLock {
- public:
- void Lock(const size_t thread_index) {
- const size_t another_thread = 1 - thread_index;
- flag[thread_index].store(true);
- victim.store(thread_index);
- while(flag[another_thread].load() && victim.load() == thread_index) {};
- }
- void Unlock(const size_t thread_index) {
- flag[thread_index].store(false);
- }
- private:
- std::atomic<bool> flag[2];
- std::atomic<size_t> victim;
- };
- class TournamentTreeLock {
- public:
- explicit TournamentTreeLock(const size_t num_threads) {
- }
- void Lock(const size_t thread_index) {
- pt.Lock(thread_index);
- }
- void Unlock(size_t thread_index) {
- pt.Unlock(thread_index);
- }
- private:
- // Tree navigation
- size_t GetParent(size_t node_index) const {
- if(node_index % 2 == 0) {
- return (node_index-2)/2;
- }
- else return (node_index-1)/2;
- }
- size_t GetLeftChild(size_t node_index) const {
- return 2*node_index+1;
- }
- size_t GetRightChild(size_t node_index) const {
- return 2*node_index+2;
- }
- size_t GetThreadLeaf(size_t thread_index) const {
- return 0;
- }
- private:
- PetersonLock pt;
- };
- } // namespace solutions
- } // namespace tpcc
Add Comment
Please, Sign In to add comment