내용 보기
작성자
관리자 (IP : 172.17.0.1)
날짜
2021-05-24 10:00
제목
[C#] ReaderWriterLockSlim은 언제 쓰는 걸까요?
|
일반적으로 C#에서는 다음과 같이 동기화를 합니다. object lockInstance = new object();
lock (lockInstance)
{
... [공유자원 접근] ...
}
void lockThread(object state)
{
int counterIndex = (int)state;
while (threadStop == false)
{
lock (lockCount)
{
counts[counterIndex]++;
}
}
}
for (int i = 0; i < count; i++)
{
Thread newThread = new Thread(lockThread);
newThread.IsBackground = true;
newThread.Start(i);
}
11904819.7152496 11949052.7475766 11931037.5872447 11933239.6103584 11881933.1463757 ==> 초당 약 12,000,000 번의 실행
Slim Reader/Writer (SRW) Locks ; https://docs.microsoft.com/en-us/windows/win32/sync/slim-reader-writer--srw--locks ReaderWriterLockSlim cacheLock = new ReaderWriterLockSlim(); void readerThread(object state) { int countIndex = (int)state; while (threadStop == false) { cacheLock.EnterReadLock(); try { counts[countIndex]++; } finally { cacheLock.ExitReadLock(); } } } void writerThread(object state) { int countIndex = (int)state; while (threadStop == false) { cacheLock.EnterWriteLock(); try { counts[countIndex]++; } finally { cacheLock.ExitWriteLock(); } } }
for (int i = 0; i < count; i++)
{
Thread newThread;
if (i == 0)
{
newThread = new Thread(writerThread);
}
else
{
newThread = new Thread(readerThread);
}
newThread.IsBackground = true;
newThread.Start(i);
}
5439175.07101596 5398816.34136504 5390411.53317197 5366829.75513943 5351321.89442379 5344019.70797552 5334268.38922098 ==> 초당 약 5,500,000 번의 실행
void lockThread(object state)
{
int counterIndex = (int)state;
while (threadStop == false)
{
lock (lockCount)
{
counts[counterIndex]++;
Thread.Sleep(1);
}
}
}
998.700954608068 998.745307936315 998.820608186942 998.825143635559 998.893010223893 ==> 초당 약 1,000 번의 실행
void readerThread(object state)
{
int countIndex = (int)state;
while (threadStop == false)
{
cacheLock.EnterReadLock();
try
{
counts[countIndex]++;
Thread.Sleep(1);
}
finally
{
cacheLock.ExitReadLock();
}
}
}
void writerThread(object state)
{
int countIndex = (int)state;
while (threadStop == false)
{
cacheLock.EnterWriteLock();
try
{
counts[countIndex]++;
Thread.Sleep(1);
}
finally
{
cacheLock.ExitWriteLock();
}
}
}
1957.41883217647 1900.581814786 1912.05442748045 1890.14059164164 1908.65293256279 ==> 초당 약 1,900 번의 실행
|
출처1
https://www.sysnet.pe.kr/Default.aspx?mode=2&sub=0&pageno=11&detail=1&wid=1179
출처2