我正在尝试在C++ 11中实现一个无锁多个生产者,多个消费者队列.我这样做是为了学习练习,所以我很清楚我可以使用现有的开源实现,但我真的很想知道为什么我的代码不起作用.数据存储在一个环形缓冲区中,显然它是一个"有界MPMC队列".
我已经将它与Disruptor的内容非常接近地建模了.我注意到的事情是它对单个消费者和单个/多个生产者来说绝对正常,它只是多个消费者似乎打破了它.
这是队列:
template <typename T>
class Queue : public IQueue<T>
{
public:
explicit Queue( int capacity );
~Queue();
bool try_push( T value );
bool try_pop( T& value );
private:
typedef struct
{
bool readable;
T value;
} Item;
std::atomic<int> m_head;
std::atomic<int> m_tail;
int m_capacity;
Item* m_items;
};
template <typename T>
Queue<T>::Queue( int capacity ) :
m_head( 0 ),
m_tail( 0 ),
m_capacity(capacity),
m_items( new Item[capacity] )
{
for( int i = 0; i < capacity; ++i )
{ …
Run Code Online (Sandbox Code Playgroud) 我收到以下错误:
class Test
{
std::map<std::string,Test> test;
};
Run Code Online (Sandbox Code Playgroud)
错误是"字段具有不完整类型'测试'".我读了一些线程,建议这可能是随xcode附带的libcxx版本中的一个错误,但如果我只需将其更改为:它就不会让我感到惊讶:
class Test
{
std::map<std::string,std::shared_ptr<Test>> test;
};
Run Code Online (Sandbox Code Playgroud)
我只想仔细检查这肯定是一个正确的错误,而不是一个错误.
干杯!
我正在编写一些线程C++ 11代码,而且我不确定何时需要使用内存栅栏或其他东西.所以基本上我正在做的事情:
class Worker
{
std::string arg1;
int arg2;
int arg3;
std::thread thread;
public:
Worker( std::string arg1, int arg2, int arg3 )
{
this->arg1 = arg1;
this->arg2 = arg2;
this->arg3 = arg3;
}
void DoWork()
{
this->thread = std::thread( &Worker::Work, this );
}
private:
Work()
{
// Do stuff with args
}
}
int main()
{
Worker worker( "some data", 1, 2 );
worker.DoWork();
// Wait for it to finish
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我想知道,我需要采取哪些步骤来确保在另一个线程上运行的Work()函数中访问args是安全的.它是否足以在构造函数中编写,然后在单独的函数中创建线程?或者我需要一个内存栅栏,如何制作一个内存栅栏以确保所有3个args都是由主线程写入的,然后由Worker线程读取?
谢谢你的帮助!