Is multiple-producer, single-consumer possible in a lockfree setting?

后端 未结 4 424
渐次进展
渐次进展 2021-02-01 09:25

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

4条回答
  •  囚心锁ツ
    2021-02-01 10:24

    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).

提交回复
热议问题