Advertisement
MystMe

Untitled

Feb 25th, 2018
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.32 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.     PetersonLock() {
  13.         flag[0].store(false);
  14.         flag[1].store(false);
  15.         victim.store(0);
  16.     }
  17.     void Lock(const size_t thread_index) {
  18.       const size_t another_thread = 1 - thread_index;
  19.       flag[thread_index].store(true);
  20.       victim.store(thread_index);
  21.       while(flag[another_thread].load() && victim.load() == thread_index) {};
  22.     }
  23.  
  24.     void Unlock(const size_t thread_index) {
  25.       flag[thread_index].store(false);
  26.     }
  27.   private:
  28.     std::atomic<bool> flag[2];
  29.     std::atomic<size_t> victim;
  30. };
  31.  
  32. class TournamentTreeLock {
  33.   public:
  34.     explicit TournamentTreeLock(const size_t num_threads) {
  35.       return;
  36.     }
  37.  
  38.     void Lock(const size_t thread_index) {
  39.       //std::cerr << "TRY LOCK " << thread_index << std::endl;
  40.       pt.Lock(thread_index);
  41.       //std::cerr << "GET LOCK " << thread_index << std::endl;
  42.     }
  43.  
  44.     void Unlock(const size_t thread_index) {
  45.       //std::cerr << "TRY UNLOCK " << thread_index << std::endl;
  46.       pt.Unlock(thread_index);
  47.       //std::cerr << "GET UNLOCK " << thread_index << std::endl;
  48.     }
  49.   private:
  50.     PetersonLock pt;
  51. };
  52.  
  53. } // namespace solutions
  54. } // namespace tpcc
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement