Slim Reader/Writer locks extremely slow, violating FIFO

badasahog 31 Reputation points
2022-12-30T02:07:49.64+00:00

for some reason when three threads try to acquire a lock simultaneously, (with some Sleep() calls added in for good measure) one of the threads doesn't get to acquire the lock quickly

my code:

include <iostream>

include <Windows.h>

SRWLOCK mainLock;
LONG myglobalvar;
int main()
{
myglobalvar = 0;
HANDLE t1 = CreateThread(nullptr, 0, ->DWORD
{
while (true)
{
AcquireSRWLockExclusive(&mainLock);
InterlockedIncrement(&myglobalvar);
Sleep(500);
ReleaseSRWLockExclusive(&mainLock);
}
return 0;
}, nullptr, 0, nullptr);
Sleep(50);
HANDLE t2 = CreateThread(nullptr, 0, ->DWORD
{
while (true)
{
AcquireSRWLockExclusive(&mainLock);
InterlockedIncrement(&myglobalvar);
ReleaseSRWLockExclusive(&mainLock);
}
return 0;
}, nullptr, 0, nullptr);
for (int i = 0; i < 100; i++)
{
AcquireSRWLockExclusive(&mainLock);
std::cout << myglobalvar << '\n';
ReleaseSRWLockExclusive(&mainLock);
Sleep(50);
}
}

Windows API - Win32
Windows API - Win32
A core set of Windows application programming interfaces (APIs) for desktop and server applications. Previously known as Win32 API.
2,422 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Xiaopo Yang - MSFT 11,496 Reputation points Microsoft Vendor
    2022-12-30T05:43:22.817+00:00

    Hello,

    Welcome to Microsoft Q&A!

    Thread t2 is in a tight loop of releasing and reacquiring the lock, which causes that the other threads (t1 and the main thread) get no chance to acquire it, as Peter said.
    Also see my answer about Slim Reader/Writer (SRW) Locks and the code.

    Thank you.

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments