Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performing a pointer swap in a double-buffer multithread system

When double-buffering data that's due to be shared between threads, I've used a system where one thread reads from one buffer, one thread reads from the other buffer and reads from the first buffer. The trouble is, how am I going to implement the pointer swap? Do I need to use a critical section? There's no Interlocked function available that will actually swap values. I can't have thread one reading from buffer one, then start reading from buffer two, in the middle of reading, that would be appcrash, even if the other thread didn't then begin writing to it.

I'm using native C++ on Windows in Visual Studio Ultimate 2010 RC.

like image 291
DeadMG Avatar asked Feb 15 '10 20:02

DeadMG


1 Answers

Using critical sections is the accepted way of doing it. Just share a CRITICAL_SECTION object between all your threads and call EnterCriticalSection and LeaveCriticalSection on that object around your pointer manipulation/buffer reading/writing code. Try to finish your critical sections as soon as possible, leaving as much code outside the critical sections as possible.

Even if you use the double interlocked exchange trick, you still need a critical section or something to synchronize your threads, so might as well use it for this purpose too.

like image 102
Blindy Avatar answered Sep 28 '22 19:09

Blindy