c++ - 为什么我不能调用我的结构信号量方法?
问题描述
我正在尝试输入小写字符并将其添加到 in.buffer,另一个线程应该从 in.buffer 读取并将其变为小写并发送到 out.buffer,最后一个应该从 out.buffer 读取并打印它。
我收到错误:数字常量信号量 m_free(10) 之前的预期标识符;错误:无效使用成员函数'Semaphore RingBuffer::m_free(int)'</p>
这是为什么?
谢谢
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
struct Semaphore
{
Semaphore() = default;
Semaphore(int x) : m_s(x) {}
void release() {
std::unique_lock<std::mutex> lock(m_mut);
m_s += 1;
m_cv.notify_one();
}
void acquire() {
std::unique_lock<std::mutex> lock(m_mut);
m_cv.wait(lock, [this](){ return m_s != 0; });
m_s -= 1;
}
private:
int m_s = 0;
std::mutex m_mut;
std::condition_variable m_cv;
};
struct RingBuffer {
void write(char x);
char read();
private:
std::array<char, 10> m_buff;
int m_w = 0;
int m_r = 0;
Semaphore m_free(10);
Semaphore m_taken(0);
std::mutex m_mut;
};
void RingBuffer::write(char x) {
m_free.acquire();
{
std::lock_guard<std::mutex> l(m_mut);
m_buff[m_w] = x;
m_w = m_w % 10 == 0 ? 0 : m_w + 1;
}
m_taken.release();
}
char RingBuffer::read() {
int res=-1;
m_taken.acquire();
{
std::lock_guard<std::mutex> l(m_mut);
res = m_buff[m_r];
m_r = m_r % 10 == 0 ? 0 : m_r + 1;
}
m_free.release();
return res;
}
int main()
{
//RING_SIZE;
RingBuffer in,out;
std::thread threadin([&in](){
//while(true){
char ch;
std::cin>>ch;
in.write(ch);
//}
});
std::thread threaddo([&in,&out](){
char ch=in.read();
ch=ch-32;
out.write(ch);
//}
});
std::thread threadout([&out](){
//while(true){
char ch=out.read();
std::cout<<ch<<std::endl;
//}
});
threadin.join();
threaddo.join();
threadout.join();
return 0;
}
解决方案
推荐阅读
- android - org.gradle.api.tasks.TaskExecutionException:任务执行失败.. 原因:org.gradle.api.internal.tasks.compile.CompilationFailedException:
- node.js - 以编程方式跨 Azure、VSTS 和 Graph 访问 Microsoft 标识
- sql - SQL Server:如何使这个查询更高效/更快?
- python - 在滚动窗口中计算不同的字符串,包括使用 pandas 的 NaN
- r - 从R中的字符串获取首字母
- java - 对象变量在 Android 中从一个线程到另一个线程不可见
- arduino - 我在 arduino 中找不到 hid.h 文件
- sql - 如何在oracle中获取特定月份的两个日期之间的日期列表
- android - ConstraintLayout 如何影响子重力?
- oracle - 如何避免警告“IMP-00041:警告:创建带有编译警告的对象”?