Skip to content
Snippets Groups Projects
Commit bb8f0ee0 authored by Florian Schmaus's avatar Florian Schmaus
Browse files

Add emper::Semaphore

parent 49b4c439
No related branches found
No related tags found
No related merge requests found
...@@ -11,6 +11,7 @@ add_files(EMPER_SOURCE Debug.cpp) ...@@ -11,6 +11,7 @@ add_files(EMPER_SOURCE Debug.cpp)
add_files(EMPER_SOURCE ContextManager.cpp) add_files(EMPER_SOURCE ContextManager.cpp)
add_files(EMPER_SOURCE BinaryPrivateSemaphore.cpp) add_files(EMPER_SOURCE BinaryPrivateSemaphore.cpp)
add_files(EMPER_SOURCE CountingPrivateSemaphore.cpp) add_files(EMPER_SOURCE CountingPrivateSemaphore.cpp)
add_files(EMPER_SOURCE Semaphore.cpp)
add_files(EMPER_INCLUDE ".") add_files(EMPER_INCLUDE ".")
add_files(EMPER_INCLUDE "include") add_files(EMPER_INCLUDE "include")
......
#include "Semaphore.hpp"
using namespace emper;
void Semaphore::print() {
unsigned int count = this->count;
unsigned int waiterListSize;
{
const std::lock_guard<std::mutex> lock(mutex);
waiterListSize = waiterList.size();
}
std::cout << "Semaphore"
<< " count=" << count
<< " waiterListSize=" << waiterListSize
<< std::endl;
}
#pragma once
#include <queue>
#include <mutex>
#include "BinaryPrivateSemaphore.hpp"
namespace emper {
class Semaphore {
private:
std::queue<BinaryPrivateSemaphore*> waiterList;
unsigned int count;
std::mutex mutex;
public:
bool acquire() {
bool blocked;
mutex.lock();
if (count > 0) {
count--;
mutex.unlock();
blocked = false;
} else {
BinaryPrivateSemaphore semaphore;
waiterList.push(&semaphore);
mutex.unlock();
semaphore.wait();
blocked = true;
}
return blocked;
}
bool release() {
mutex.lock();
bool waiterListEmpty = waiterList.empty();
if (waiterListEmpty) {
count++;
mutex.unlock();
} else {
BinaryPrivateSemaphore* semaphore = waiterList.front();
waiterList.pop();
mutex.unlock();
semaphore->signal();
}
return waiterListEmpty;
}
void print();
};
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment