也许我没有正确理解这个想法,但显而易见的解决方案就是std::atomic
对当前数组索引使用增量。整数类型的原子通常实现为无锁。
但是,如果这不是真的或者您的编译器不支持 C++11,您可以将其替换为您的编译器特定的无锁函数,例如InterlockedIncrement
VS 或__sync_fetch_and_add
GCC。
支持英特尔 C++ 编译器C++ 11 atomics
。您也可以_InterlockedIncrement64
从头ia64intrin.h
文件中使用,请参阅第 147 页的Intel(R) C++ Intrinsics Reference
.
示例代码(证明它在这里工作)
#include <atomic>
#include <thread>
#include <iostream>
const uint max_count = 100;
std::atomic_uint count;
std::string data[max_count];
void thread_func(const char* str)
{
while(true)
{
const uint index = count++;
if(index >= max_count) break;
// Use += to see defect if data was already initialized by other thread
data[index] += str;
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
}
int main()
{
std::cout << "Atomic counter is lock-free: " <<
(count.is_lock_free() ? "Yes!" : "No!") << std::endl;
std::thread t1(thread_func, "Thread 1");
std::thread t2(thread_func, "Thread 2");
std::thread t3(thread_func, "Thread 3");
t1.join();
t2.join();
t3.join();
for(uint i = 0; i < max_count; ++i)
{
std::cout<< i << ": " << data[i] << std::endl;
}
return 0;
}