首页 > 解决方案 > 为什么我不能调用我的结构信号量方法?

问题描述

我正在尝试输入小写字符并将其添加到 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;
}

标签: c++multithreadingc++17mutex

解决方案


您不能在struct. Astruct包含其成员的定义,而不是代码。

您可以在构造函数中初始化成员:

struct RingBuffer {
    Semaphore m_free;
    RingBuffer() : m_free(10) {} // constructor with a member-initializer-list
};

或使用默认成员初始化器内联:

struct RingBuffer {
    Semaphore m_free {10};
};

或者

struct RingBuffer {
    Semaphore m_free = 10;
};

但是没有语法可以使用().


推荐阅读