我必须开发一个具有以下特征的信号量结构:
- 有一个关键部分,最多
Capacity 个线程可以同时进入和执行。执行后线程退出临界区;
- 当信号量达到最大容量,执行队列被填满时:队列中的线程进入休眠状态,当其他线程退出临界区时被唤醒;
- 执行队列具有 FIFO 语义;
- 有一种通知机制可以通知等待线程它们在队列中的位置;
- 只允许进入临界区的线程退出。
第 1-2 点通常描述理论上的 semaphore 数据类型,而第 3-4 点则要求其他行为/API 约束和功能。毫不奇怪,这种结构可以仅使用 mutex 和 条件变量 原语来构建,即使信号量本身经常被误认为是同步原语。它遵循 C++11 实现,也可以移植到提供上述原语的任何语言/环境。由于通知机制要求不要使信号量锁保持忙碌,因此该实现并非完全微不足道。自定义优先级和优先级编辑尚未实现,因为我不需要类似调度程序的功能,但它们应该也是可能的。
Semaphore.h
#pragma once
#include <condition_variable>
#include <mutex>
#include <thread>
#include <functional>
#include <list>
namespace usr
{
typedef std::function<void(unsigned processIndex)> SemaphoreNotifier;
class Semaphore;
class SemaphoreToken final
{
friend class Semaphore;
public:
SemaphoreToken();
private:
SemaphoreToken(Semaphore &semaphore);
private:
void Invalidate();
private:
Semaphore *Parent;
std::thread::id ThreadId;
};
class SemaphoreCounter final
{
friend class Semaphore;
public:
SemaphoreCounter();
private:
void Increment();
public:
unsigned GetCount() const { return m_count; }
private:
unsigned m_count;
};
class Semaphore final
{
class Process
{
public:
Process(unsigned index);
public:
void Wait();
void Set();
void Decrement();
void Detach();
public:
bool IsDetached() const { return m_detached; }
unsigned GetIndex() const { return m_index; }
private:
std::mutex m_mutex;
unsigned m_index; // Guarded by m_mutex
bool m_detached; // Guarded by m_mutex
std::unique_lock<std::mutex> m_lock;
std::condition_variable m_cond;
};
public:
Semaphore(unsigned capacity = 1);
public:
SemaphoreToken Enter();
SemaphoreToken Enter(SemaphoreCounter &counter, unsigned &id);
SemaphoreToken Enter(const SemaphoreNotifier ¬ifier);
SemaphoreToken Enter(const SemaphoreNotifier ¬ifier, SemaphoreCounter &counter, unsigned &id);
bool TryEnter(SemaphoreToken &token);
bool TryEnter(SemaphoreCounter &counter, unsigned &id, SemaphoreToken &token);
void Exit(SemaphoreToken &token);
private:
bool enter(bool tryEnter, const SemaphoreNotifier ¬ifier, SemaphoreCounter *counter, unsigned &id, SemaphoreToken &token);
private:
// Disable copy constructor and assign operator
Semaphore(const Semaphore &);
Semaphore & operator=(const Semaphore &);
public:
unsigned GetCapacity() const { return m_capacity; }
private:
mutable std::mutex m_mutex;
unsigned m_capacity;
unsigned m_leftCapacity; // Guarded by m_mutex
std::list<Process *> m_processes; // Guarded by m_mutex
};
}
信号量.cpp
#include "Semaphore.h"
#include <cassert>
#include <limits>
#include <algorithm>
using namespace std;
using namespace usr;
Semaphore::Semaphore(unsigned capacity)
{
if (capacity == 0)
throw runtime_error("Capacity must not be zero");
m_capacity = capacity;
m_leftCapacity = capacity;
}
SemaphoreToken Semaphore::Enter()
{
unsigned id;
SemaphoreToken token;
enter(false, nullptr, nullptr, id, token);
return token;
}
SemaphoreToken Semaphore::Enter(SemaphoreCounter &counter, unsigned &id)
{
SemaphoreToken token;
enter(false, nullptr, &counter, id, token);
return token;
}
SemaphoreToken Semaphore::Enter(const SemaphoreNotifier ¬ifier)
{
unsigned id;
SemaphoreToken token;
enter(false, notifier, nullptr, id, token);
return token;
}
SemaphoreToken Semaphore::Enter(const SemaphoreNotifier ¬ifier,
SemaphoreCounter &counter, unsigned &id)
{
SemaphoreToken token;
enter(false, notifier, &counter, id, token);
return token;
}
bool Semaphore::TryEnter(SemaphoreToken &token)
{
unsigned id;
return enter(true, nullptr, nullptr, id, token);
}
bool Semaphore::TryEnter(SemaphoreCounter &counter, unsigned &id, SemaphoreToken &token)
{
return enter(true, nullptr, &counter, id, token);
}
bool Semaphore::enter(bool tryEnter, const SemaphoreNotifier ¬ifier,
SemaphoreCounter *counter, unsigned &id, SemaphoreToken &token)
{
unique_lock<mutex> lock(m_mutex);
if (counter != nullptr)
{
id = counter->GetCount();
counter->Increment();
}
if (m_leftCapacity > 0)
{
// Semaphore is availabile without accessing queue
assert(m_processes.size() == 0);
m_leftCapacity--;
}
else
{
if (tryEnter)
return false;
Process process((unsigned)m_processes.size());
unsigned previousIndex = numeric_limits<unsigned>::max();
m_processes.push_back(&process);
// Release semaphore unlock
lock.unlock();
NotifyAndWait:
unsigned index = process.GetIndex();
if (notifier != nullptr && index != 0 && index != previousIndex)
{
try
{
// Notify the caller on progress
notifier(index);
}
catch (...)
{
// Retake Semaphore lock
lock.lock();
// Remove the failing process
auto found = std::find(m_processes.begin(), m_processes.end(), &process);
auto it = m_processes.erase(found);
for (; it != m_processes.end(); it++)
{
// Decrement following processes
auto &otherProcess = **it;
otherProcess.Decrement();
otherProcess.Set();
}
// Rethrow. NOTE: lock will be unlocked by RAII
throw;
}
previousIndex = index;
}
process.Wait();
if (!process.IsDetached())
goto NotifyAndWait;
}
token = SemaphoreToken(*this);
return true;
}
void Semaphore::Exit(SemaphoreToken &token)
{
if (this != token.Parent || token.ThreadId != this_thread::get_id())
throw runtime_error("Exit called from wrong semaphore or thread");
{
unique_lock<mutex> lock(m_mutex);
if (m_processes.size() == 0)
{
m_leftCapacity++;
}
else
{
auto front = m_processes.front();
m_processes.pop_front();
front->Detach();
front->Set();
for (auto process : m_processes)
{
process->Decrement();
process->Set();
}
}
token.Invalidate();
}
}
SemaphoreToken::SemaphoreToken() :
Parent(nullptr)
{
}
SemaphoreToken::SemaphoreToken(usr::Semaphore &semaphore) :
Parent(&semaphore),
ThreadId(this_thread::get_id())
{
}
void SemaphoreToken::Invalidate()
{
Parent = nullptr;
ThreadId = thread::id();
}
SemaphoreCounter::SemaphoreCounter()
: m_count(0)
{
}
void SemaphoreCounter::Increment()
{
m_count++;
}
Semaphore::Process::Process(unsigned index) :
m_index(index),
m_detached(false),
m_lock(m_mutex)
{
}
void Semaphore::Process::Wait()
{
m_cond.wait(m_lock);
}
void Semaphore::Process::Set()
{
m_cond.notify_one();
}
void Semaphore::Process::Decrement()
{
unique_lock<mutex> lock(m_mutex);
assert(m_index > 0);
m_index--;
}
void Semaphore::Process::Detach()
{
unique_lock<mutex> lock(m_mutex);
assert(m_index == 0);
m_detached = true;
}
我使用以下示例代码对其进行了测试:
SemaphoreCounter counter;
Semaphore semaphore(4); // Up to 4 threads can execute simultaneously
vector<shared_ptr<thread>> threads;
int threadCount = 300;
for (int i = 0; i < threadCount; i++)
{
threads.push_back(std::make_shared<thread>([&semaphore, &counter]
{
unsigned threadId;
auto token = semaphore.Enter([&threadId](unsigned index) {
cout << "Thread " << threadId << " has " << index << " processes ahead before execution" << endl;
}, counter, threadId);
cout << "EXECUTE Thread " << threadId << endl;
std::this_thread::sleep_for(15ms);
semaphore.Exit(token);
}));
}
for (int i = 0; i < threadCount; i++)
threads[i]->join();