(两个误解答案之后的澄清:如果生产者线程的数量小于堆栈大小,则代码工作正常。只有1个消费者释放插槽。我用32个生成器VS 16个插槽调整此演示的方式是触发一个糟糕的情况很快)
在对用于多线程缓冲区管理的无锁堆栈进行压力测试时,我发现无法保证缓冲区内容的完整性。我现在很确定堆栈/ LIFO解决方案不是最佳选择;但我仍然想了解这些缓冲区是如何受到损害的。
这个想法是:一个无锁堆栈,包含指向“空闲”缓冲区的指针。它们可以由许多生产者线程中的一个检索。然后缓冲区填充数据并“分派”到单个使用者线程,最终将它们返回到堆栈。
观察结果是: - 两个线程以某种方式获得相同的缓冲区。 - 一个线程正在获取一个缓冲区,其内存仍然没有从刚刚释放它的其他线程中刷新。
这是我为了演示而可以放在一起的最简单的例子:
更新:我为想要使用它的人创建了一个具有更好调试输出的版本,在这里:https://ideone.com/v9VAqU
#include <atomic>
#include <assert.h>
#include <chrono>
#include <iostream>
#include <mutex>
#include <queue>
#include <thread>
using namespace std;
#define N_SLOTS 16
#define N_THREADS 32
// The data buffers that are shared among threads
class Buffer { public: int data[N_THREADS] = {0}; } buffers[N_SLOTS];
// The lock-free stack under study
class LockFreeStack
{
Buffer* stack[N_SLOTS];
atomic_int free_slots, out_of_slots, retries;
public:
LockFreeStack() : free_slots(0), out_of_slots(0), retries(0) {
for (int i=0; i<N_SLOTS; i++)
release_buffer(&buffers[i]);
}
Buffer* get_buffer()
{
int slot = --free_slots;
if (slot < 0) {
out_of_slots++;
return nullptr;
}
/// [EDIT] CAN GET PREEMPTED RIGHT HERE, BREAKING ATOMICITY!
return stack[slot];
}
void release_buffer(Buffer* buf)
{
int slot;
while(true) {
slot = free_slots;
if (slot <= 0) {
stack[0] = buf;
free_slots = 1;
break;
}
stack[slot] = buf;
if (free_slots++ == slot)
break;
retries++;
}
}
ostream& toStream(ostream& oss) {
return oss << "LockFreeStack with free_slots=" << free_slots << ", oos=" << out_of_slots << ", retries=" << retries;
}
} lockFreeStack;
// Utility class to help with test
class PrintQueue {
queue<Buffer*> q;
mutex m;
public:
void add(Buffer* buf) {
lock_guard<mutex> lock(m);
q.push(buf);
}
Buffer* pop() {
lock_guard<mutex> lock(m);
Buffer* buf;
if (q.empty())
return nullptr;
buf = q.front();
q.pop();
return buf;
}
} printQueue;
int main()
{
vector<thread> workers;
for (int t = 0; t < N_THREADS; ++t) {
workers.push_back(thread([&,t] {
while(true) {
auto buf = lockFreeStack.get_buffer();
if (buf) {
buf->data[t] = t;
this_thread::sleep_for(chrono::milliseconds(10));
printQueue.add(buf);
}
}
}));
}
while(true) {
this_thread::sleep_for(chrono::milliseconds(10));
lockFreeStack.toStream(cout) << endl;
Buffer *buf;
while((buf = printQueue.pop())) {
cout << "Got Buffer " << buf << " #" << (buf-buffers) << " { ";
int used = 0;
for(int t=0; t<N_THREADS; t++)
if (buf->data[t]) {
used += 1;
cout << 't' << buf->data[t] << ' ';
buf->data[t] = 0;
}
cout << "}\n";
assert (used == 1);
lockFreeStack.release_buffer(buf);
}
}
return 0;
}
输出错误的样本:
> LockFreeStack with free_slots=-2454858, oos=2454836, retries=0
> Got Buffer 0x604a40 #12 { t7 }
> Got Buffer 0x6049c0 #11 { t8 }
> Got Buffer 0x604b40 #14 { t1 }
> Got Buffer 0x604bc0 #15 { }
> test.cpp:111: int main(): Assertion `used == 1' failed.
我已尝试在所有地方使用std::atomic_thread_fence()
,但这没有任何区别。
错误在哪里?
(顺便说一句,经过多个版本的GCC测试,包括5.2和4.6)
答案 0 :(得分:2)
您的LockFreeStack代码已完全损坏。
同时从2个线程调用的 release_buffer
可以在同一个插槽中粘贴2个指针,因此丢失了一个。
if (free_slots++ == slot)
只会对一个线程成功,所以另一个会再次尝试并将其指针放在另一个槽中。但它也可能是在第一个插槽中赢得的那个,所以你得到相同但在2个插槽中。
您可以通过1个线程调用release_buffer
和另一个调用get_buffer
获得相同的效果。这些情景中的一个或两个都会导致您的腐败。
release_buffer
的大小不会超过stack
,所以预计缓冲区会超出,然后所有地狱都会崩溃。
我建议:
release_buffer
首先选择唯一广告位原子,然后写信给它。
当多个发布者竞争插槽时,插槽中指针的写入顺序不是保证,因此您需要一些其他方法将插槽标记为release_buffer
上的有效,并在{{1 }}。最简单的方法是在get_buffer
中将其取消。
将计数器绑定到堆栈的大小。如果你不能做一个原子操作,拿一个副本,做所有的改变,然后再把它改回来。
修改强>
这是一个将相同缓冲区返回到2个单元格的场景:
get_buffer
编辑2:断言失败......
如果你现在还没找到,那就是:
////T==0 free_slots==5
// thread 1
void release_buffer(Buffer* buf) ////T==1 buf==buffers[7]
{
int slot;
while(true) { //// 1st iteration
slot = free_slots; ////T==2 free_slots==5 slot==5
if (slot <= 0) {
stack[0] = buf;
free_slots = 1;
break;
} ////*** note other threads below ***
stack[slot] = buf; //// stack[5]==buffers[7]
if (free_slots++ == slot) ////T==5 free_slots==4 slot==5 ---> go for another round
break;
retries++;
}
while(true) { //// 2nd iteration
slot = free_slots; ////T==6 free_slots==4 slot==4
if (slot <= 0) {
stack[0] = buf;
free_slots = 1;
break;
}
stack[slot] = buf; //// stack[4]==buffers[7] //// BOOM!!!!
if (free_slots++ == slot) ////T==7 free_slots==5 slot==4 ---> no other round
break;
retries++;
}
}
// thread 2
Buffer* get_buffer() // thread
{
int slot = --free_slots; ////T==3 free_slots==4
if (slot < 0) {
out_of_slots++;
return nullptr;
}
return stack[slot];
}
// thread 3
Buffer* get_buffer()
{
int slot = --free_slots; ////T==4 free_slots==3
if (slot < 0) {
out_of_slots++;
return nullptr;
}
return stack[slot];
}
在缓冲区中写入t + 1将修复它。
答案 1 :(得分:0)
感谢您的想法。我最终发现了这个问题:
现在最初在堆栈[N-1]中的指针已经丢失(内存泄漏),并且get_buffer()的下一个线程将与线程#2相同,如果它在同一时间唤醒的话。
答案 2 :(得分:-1)
我在Linux上使用gcc 5.3编译并执行了以下命令:
#include <atomic>
#include <iostream>
int main()
{
for (int i=0; i<5; ++i)
{
std::atomic_int n;
std::cout << n << std::endl;
n=4;
}
return 0;
}
结果输出如下:
306406976
4
4
4
4
由此我得出结论,std::atomic_int
的构造函数没有明确地清除原子整数的初始值。必须明确初始化它。我想验证这个事实,因为我对原子库不太熟悉。我的结果表明std::atomic_int
必须显式初始化,它们不会自动初始化为0。
根据以下观察结果,系统提示我验证std::atomic_int
是否正在初始化:
此处,LockFreeStack
构造函数未显式初始化std::atomic_int
类成员。
构造函数调用release_buffer()
方法。
release_buffer
()方法会读取并使用free_slots
。
由此,我必须得出结论,这是未定义的行为。