Hello guys :D

Hello guys :D

Is there a way to create memory barriers in Delphi? Something like .NET's System.Threading.Barrier class, java.util.concurrent.CyclicBarrier from Java or pthread_barrier for C.

I have looked at Delphi Documentation but I cannot find anything like it :'(

Thanks in advance :D

Comments

  1. Stefan Glienke​ Thanks, unfortunately no :'( I meant something like .NET's System.Threading.Barrier, java.util.concurrent.CyclicBarrier from Java or pthread_barrier for C.

    ReplyDelete
  2. Just use an asm block

    That said on x86 (64 or not) the usage cases of memory barriers is quite corner-case, in very low-level lock-free code.

    If you want to replace volatile, use atomic ops, or light-weight locks, they usually have a better performance profile in heavy multi-threading than barriers. A full barrier can sometimes be like using a sledge hammer to swat a mosquito :)

    ReplyDelete
  3. Eric Grange and the performance can be like carrying a sledgehammer when you only need a flyswat. Nothing like watching the whole system grind to halt thousands of times a second while some ill-thought barrier grinds through.

    ReplyDelete
  4. Wouldn't an array of manual-reset events (one per thread) be sufficient to implement this? Each thread sets it's event, waits for all events and then resets it's own event afterwards?

    ReplyDelete
  5. Horácio Filho Needed a distraction, so whipped up a simple implementation: https://github.com/lordcrc/ThreadBarrier 

    Condition variables might perform better, didn't have time to try.

    ReplyDelete
  6. Just for the record, the initial implementation (using events) had a race condition. I replaced the implementation with one using condition variables. Should be race free, at least as far as I can figure.

    In addition it now uses SyncObjs and not WinAPI directly, so should be portable.

    With 8 threads (4-core HT CPU) each barrier call is about 3-4 microseconds, and seems to scale linarly with thread count, at last up to 80 threads. I'm sure this can be improved, I didn't do any particular cache optimizations.

    I imagine it's fairly trivial to augment the implementation to handle a cancellation token ala .Net, if that's of interest.

    ReplyDelete
  7. Hey Asbjørn Heid, you are a genius, it is too amazing, really pretty nice :D
    It is actually I was looking for :D Many thanks.

    Java implements barriers using conditional variables and .NET does the same using manual-reset events, I don't know how is the winner :D

    ReplyDelete
  8. Horácio Filho You're welcome. 

    Condition variables are more easily ported I guess, events usually have to be implemented using something else on other systems, while condition variables are native on both Windows and POSIX.

    ReplyDelete

Post a Comment