Advertisement
MystMe

Untitled

Feb 25th, 2018
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.40 KB | None | 0 0
  1. #pragma once
  2.  
  3. #include <iostream>
  4. #include <atomic.hpp>
  5. #include <support.hpp>
  6.  
  7. namespace tpcc {
  8. namespace solutions {
  9.  
  10. class PetersonLock {
  11.   public:
  12.     void Lock(const size_t thread_index) {
  13.       const size_t another_thread = 1 - thread_index;
  14.       flag[thread_index].store(true);
  15.       victim.store(thread_index);
  16.       while(flag[another_thread].load() && victim.load() == thread_index) {};
  17.     }
  18.  
  19.     void Unlock(const size_t thread_index) {
  20.       flag[thread_index].store(false);
  21.     }
  22.   private:
  23.     std::atomic<bool> flag[2];
  24.     std::atomic<size_t> victim;
  25. };
  26.  
  27. class TournamentTreeLock {
  28.   public:
  29.     explicit TournamentTreeLock(const size_t num_threads) {
  30.     }
  31.  
  32.     void Lock(const size_t thread_index) {
  33.       pt.Lock(thread_index);
  34.     }
  35.  
  36.     void Unlock(size_t thread_index) {
  37.       pt.Unlock(thread_index);
  38.     }
  39.  
  40.   private:
  41.   // Tree navigation
  42.  
  43.     size_t GetParent(size_t node_index) const {
  44.       if(node_index % 2 == 0) {
  45.         return (node_index-2)/2;
  46.       }
  47.       else return (node_index-1)/2;
  48.     }
  49.  
  50.     size_t GetLeftChild(size_t node_index) const {
  51.       return 2*node_index+1;
  52.     }
  53.  
  54.     size_t GetRightChild(size_t node_index) const {
  55.       return 2*node_index+2;
  56.     }
  57.  
  58.     size_t GetThreadLeaf(size_t thread_index) const {
  59.       return 0;
  60.     }
  61.  
  62.   private:
  63.     PetersonLock pt;
  64. };
  65.  
  66. } // namespace solutions
  67. } // namespace tpcc
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement