Wednesday, April 29, 2009

Memory Barriers in multi-threaded applications

Sometimes, the compiler can get in the way and break your code because it makes single-thread assumptions about your code. In addition, the microprocessors can break your code because it makes single-core assumptions. The way to fix this is use a memory barrier.

Here is a very good description of the problem of multi-threading.


Here is how to do it on a PowerPC, using the lwsync instruction.

volatile unsigned variable1 = 0;

#define barrier() __asm__ volatile (”lwsync”)

#define ITERATIONS 50000000

void *writer(volatile unsigned *variable2) {
utilBindThreadToCPU(0);
for (;;) {
variable1 = variable1 + 1;
barrier();
*variable2 = *variable2 + 1;
}
return NULL;
}

No comments: