I have a bunch of threads that are doing lots of communication with each other. I would prefer this be lock free.
For each thread, I want to have a mailbox, where other
Sure, if you have an atomic CompareAndSwap
instruction:
for (i = 0; ; i = (i + 1) % MAILBOX_SIZE)
{
if ((mailbox[i].owned == false) &&
(CompareAndSwap(&mailbox[i].owned, true, false) == false))
break;
}
mailbox[i].message = message;
mailbox[i].ready = true;
After reading a message, the consuming thread just sets mailbox[i].ready = false; mailbox[i].owned = false;
(in that order).