C++ 11实现信号量
程序员文章站
2022-06-04 21:50:38
...
/************************************/
/* 文件名:CSemaphore.h */
/* 功 能:C++11信号量 */
/************************************/
#ifndef _CSEMAPHORE_H_
#define _CSEMAPHORE_H_
#include <mutex>
#include <condition_variable>
class CSemaphore
{
public:
CSemaphore(long count = 0);
void Signal();
void Wait();
private:
std::mutex _mutex;
std::condition_variable _cv;
long m_count;
};
#endif /*_CSEMAPHORE_H_*/
/************************************/
/* 文件名:CSemaphore.cpp */
/* 功 能:C++11信号量 */
/************************************/
#include "CSemaphore.h"
CSemaphore::CSemaphore(long count)
:m_count(count)
{
}
void CSemaphore::Signal()
{
std::unique_lock<std::mutex> lock(_mutex);
++m_count;
_cv.notify_one();
}
void CSemaphore::Wait()
{
std::unique_lock<std::mutex> lock(_mutex);
_cv.wait(lock, [=] {return m_count > 0; });
--m_count;
}
/* 信号量使用示例 */
#include "CSemaphore.h"
#include <iostream>
const int BufferSize = 128;
const int DataSize = 500;
int buff[BufferSize];
CSemaphore freeSpace(BufferSize);//写入线程
CSemaphore usedSpace(-100);//消费线程
std::mutex m;
void producer()
{
for (int i = 0; i < DataSize; i++)
{
freeSpace.Wait();
std::thread::id thread_id = std::this_thread::get_id();
buff[i%BufferSize] = i;
printf("Thread %d,生产 %d\n", thread_id, i);
usedSpace.Signal();
Sleep(50);
}
}
void consumer()
{
for (int i = 0; i < DataSize; i++)
{
usedSpace.Wait();
std::thread::id thread_id = std::this_thread::get_id();
printf("Thread %d,消费的数字 %d\n", thread_id, buff[i%BufferSize]);
freeSpace.Signal();
}
}
int main()
{
std::thread threads1(producer);
std::thread threads2(consumer);
threads1.join();
threads2.join();
std::cout << "完成!" << std::endl;
std::cin.get();
return 0;
}