简体   繁体   中英

Cyclic Barriers for n threads can also handle n*2 threads

I have implemented a simple Cyclic Barrier but from quick test I have realised that if you set up a barrier for, say 2 threads, but have 4 threads about to reach the barrier.await() then you will get 2 instances of pairs of threads in the critical section at the same time. Similarly using 6 threads would get 3 pairs of threads in the critical section at the same time (haven't tested very well as I am new to this)

My question is, if n threads pass the barrier and enter the critical section, how do I stop other groups of n threads entering the critical section while the critical section is already in use?

Thanks in advance.

After n'th thread arrive, all n will immediately will be allowed to cross barrier and contend for critical section. (n+1)'th to (2n-1)'th will again be waiting until 2n'th thread arrive at barrier, once arrive, all of (n+1)' th to 2n' th will cross the barrier together and contend for critical section. You can have an AtomicInteger initialized at 0 and increment it every time just before your critical section. also put a check if its value becomes n, then block/exit/return all further threads.

By the way only AtomicInteger increment and checking it has become n, is sufficient, for n threads to be allowed,and remaining to reject, what Cyclic Barrier will do here if used is, will cause all first n thread to contend for critical section together. (if only one thread should be executing code portion then only call it critical section or else call it "n thread allowed region ") Like if people waiting to eat on a dinner table are not allowed to eat until there are at least n people, and once there are n people, all allowed together to jump on the dinner :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM