Reputation: 30048
colleague and me discussed a hypothetical problem when one would want to implement spinlock mutex with std::atomic_flag
, but also implement that spinlock as not while(true) but as a
while(true)
{
cnt=0;
while (cnt<yieldAfterTries)
{
//try to get lock
cnt++;
}
std::this_thread::yield();
// if got lock do work and then break;
}
Basically idea is that the thread cant block others "for a very long time" even if it has a real time priority because it will yield after a while... but when I saw specification of std::yield I was surprised it is a suggestion, not a mandatory thing.
Provides a hint to the implementation to reschedule the execution of threads, allowing other threads to run.
http://en.cppreference.com/w/cpp/thread/yield
So can that be problematic?
Upvotes: 1
Views: 1669
Reputation: 218860
I've written code very similar to yours, and measured the impact of the call to yield
under high contention conditions. I've found the use of yield
in this way beneficial to overall system throughput.
The actual specification is not different in spirit from what you quote, but here is the exact spec from 30.3.2 [thread.thread.this], paragraphs 2 and 3:
void this_thread::yield() noexcept;
Effects: Offers the implementation the opportunity to reschedule.
Synchronization: None.
If the implementation implements yield
as a no-op (for example), this will impact only the performance of your code and not the correctness. A failing spin-lock will eventually get pre-empted even without the yield
. But it will also be more likely to needlessly hog cpu, degrading overall system performance.
Upvotes: 6
Reputation: 1243
A spinlock will be automatically pre-empted by the OS scheduler making this code unnecessary. The OS will automatically switch to another thread when one thread has taken its share of time. This is why yield is a hint. In the Completely Fair Schedular in Linux, for example, the call to yield would often cause needless context switches due to the schedular trying to correct for a thread not getting it's fair share of time.
Your attempt to get a spinlock will not block anything, only holding the spinlock will cause other things to block.
Upvotes: 1