信号量的实现和使用

#include
#include
#include<condition_variable>
#include
#include
using namespace std;
class Semaphore
{
public:
explicit Semaphore(unsigned int count);
~Semaphore();
public:
void wait();
void signal();
private:
int m_count;
std::mutex m_mutex;
std::condition_variable m_condition_variable;
};
Semaphore::Semaphore(unsigned int count) :m_count(count)
{}
Semaphore::~Semaphore()
{}
void Semaphore::wait()
{
std::unique_lockstd::mutex unique_lock(m_mutex);
–m_count;
while (m_count < 0)
{
m_condition_variable.wait(unique_lock);
}
}
void Semaphore::signal()
{
std::lock_guardstd::mutex lg(m_mutex);
if (++m_count < 1)
{
m_condition_variable.notify_one();
}
}
constexpr unsigned MAX_COUNT = 10;
constexpr unsigned MAX_THREAD = 4;

unsigned getNext(unsigned current, bool order)
{
if (order)
{
unsigned next = current + 1;
return next%MAX_THREAD;
}
else
{
unsigned next = current - 1;
return next%MAX_THREAD;
}
}
class File
{
public:
File(const std::string &name = “0”)
:m_name(name)
, m_buffer(MAX_COUNT, ‘0’)
, m_pos(0) {}
void write(char c)
{
m_buffer.at(m_pos++) = c;
}
std::string getName()const
{
return m_name;
}
std::string getData()const
{
return m_buffer;
}
private:
std::string m_name;
std::string m_buffer;
size_t m_pos;
};
Semaphore t1(1), t2(1), t3(1), t4(1);
Semaphore *semaphoreArray[MAX_THREAD] = { &t1,&t2,&t3,&t4 };
File files[MAX_THREAD] = { File(“A”),File(“B”),File(“C”),File(“D”) };
unsigned currentFile[MAX_THREAD] = { 0,1,2,3 };
void write(unsigned threadid)
{
const char c = ‘1’ + threadid;
auto &fid = currentFile[threadid];
auto nextthreadid = getNext(threadid, true);
unsigned count = 0;
while (MAX_COUNT != count)
{
//要知道自己的下一个线程,要唤醒它,也要知道自己需要执行的下一个线程。
/*四个线程分别写1,2,3,4。函数参数0,1,2,3分别表示四个线程,四个线程分别负责写1,2,3,4
因为c是不变的。线程0,wait之后(假设fid为2),files.[fid].write©执行,在fid(2)文件写入‘1’,
然后0线程开始找需要写入1的文件,12341234可知道下一个需要写入1的是2的前一个。
在当前文件在写入1,之后需要写入2,那么唤醒一个写2的线程。先这么理解吧

	*/
	semaphoreArray[threadid]->wait();
	files[fid].write(c);
	semaphoreArray[nextthreadid]->signal();
	fid = getNext(fid, false);
	++count;
}

}
int main()
{
std::cout << “hello” << std::endl;
std::thread threads[MAX_THREAD];
for (unsigned i = 0; i != MAX_THREAD; ++i)
{
threads[i] = std::thread(write, i);
}
for (auto &thread : threads)
{
thread.join();
}
for (const auto &file : files)
{
std::cout<<file.getName() << “:” << file.getData() << std::endl;
}
cout << “bye” << endl;
system(“pause”);
return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值