is there a known, working code to add elements to a shared, initialized c-style array (of objects) in multiple threads simultaneously without having to use lock on that resource? i mean, to a continuous memory block where elements are not linked by pointers.
i mean, algorithm, not libraries etc.
i just want to fill an array with elements in, say, 20 threads without locks or having to specify array ranges for threads where to fill (much like lockfree linked lists).
im using slackware 13.37 64 bit, pthreads, intel c++ compiler, tcmalloc allocator.
update : thanks guys for your answers, you all have been helpful with your ideas; if i could, i would mark all your ideas as answers. however, im still struggling with my code. so ill put the code up later in another thread to see whats happening exactly with my code, so people could really focus.
Maybe I didn’t get the idea correctly, but the obvious solution is just to use
std::atomicincrement for current array index. Atomics on integral types are usually implemented as lock-free.But if this is not true or your compiler doesn’t support C++11 you could just replace it with your compiler-specific lock-free function, e.g.
InterlockedIncrementfor VS or__sync_fetch_and_addfor GCC.For Intel C++ Compiler
C++ 11 atomicsare supported. Also you could use_InterlockedIncrement64fromia64intrin.hheader file, see page 147 ofIntel(R) C++ Intrinsics Reference.Sample code (proof that it works here)