๐Ÿ™‡โ€โ™€๏ธReaderWriterLock

  • ์ฝ์„๋•Œ(get)๋Š” ๋ฝ์ด ์—†๋Š” ๊ฒƒ์ฒ˜๋Ÿผ ์‚ฌ์šฉํ• ์ˆ˜ ์žˆ์ง€๋งŒ ์“ธ๋•Œ๋Š” ๋ฝ์„ ๊ฑธ์–ด์„œ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ
  • ReaderWriterLockSlim์ด ์ตœ์‹ ๋ฒ„์ „!!
  • ๋Œ€๋ถ€๋ถ„ ๋ฝ์ด ํ•„์š”์—†์ง€๋งŒ ์ ์€ ํ™•๋ฅ ๋กœ ๋ฝ์ด ํ•„์š”ํ• ๋•Œ ์‚ฌ์šฉํ•œ๋‹ค

๐ŸชLock, SpinLock

  • ๋ฝ์„ ๊ตฌํ˜„ํ•˜๋Š” ๋ฐฉ๋ฒ•
    • ๊ทผ์„ฑ(์Šคํ•€๋ฝ)
    • ์–‘๋ณด(yield)
    • ๊ฐ‘์งˆ(์ด๋ฒคํŠธ ๋ฐฉ์‹)

์ƒํ˜ธ๋ฐฐ์ œ์ 

static Object _lock = new object();
static SpinLock _lock2 = new SpinLock(); // ๋„ˆ๋ฌด ์˜ค๋ž˜๊ฑธ๋ฆฌ๋ฉด ์–‘๋ณดํ•จ

static void Main(string[] args)
{
    lock (_lock)
    {

    }

    bool lockTacken = false; // ์Šคํ•€๋ฝ์€ ๋ถˆ๊ฐ’์˜ ํ‚ค๊ฐ€ ํ•„์š”ํ•จ
    try
    {
        _lock2.Enter(ref lockTacken);
    }
    finally
    {
        if (lockTacken)
            _lock2.Exit();
    }
}

๋ฝ์€ ๋‚ด๋ถ€์ ์œผ๋กœ Monitor๋กœ ๊ตฌํ˜„๋จ

์ผ๋ฐ˜์ ์ธ๊ฒฝ์šฐ ๊ทธ๋ƒฅ lock()์„ ์‚ฌ์šฉํ•˜๋ฉด ๋ ๊ฑฐ๊ฐ™์Œ - ํŽธํ•ด๋ณด์ž„

์Šคํ•€๋ฝ์€ boolํ‚ค๊ฐ€ ํ•„์š”ํ•˜๊ณ  try, finally๋กœ ๋“ค์–ด๊ฐ€๊ณ  ๋‚˜๊ฐ€์•ผ ๋จ

๐ŸชReaderWriterLock์˜ˆ์‹œ

// RWLock ReaderWriterLock
// Getํ•  ๋–„๋Š” lock์„ ๊ฑธ์ง€ ์•Š๊ณ , Writeํ•  ๋•Œ๋Š” lock์„ ๊ฑฐ๋Š” Lock
static ReaderWriterLockSlim _lock3 = new ReaderWriterLockSlim();

class Reward
{

}

static Reward GetRewardById(int id)
{
    _lock3.EnterReadLock();

    _lock3.ExitReadLock();
    return null;
}

static void AddReward(Reward reward)
{
    _lock3.EnterWriteLock();

    _lock3.ExitWriteLock();
}

์ฝ์„ ๋• ํŽธํ•˜๊ฒŒ ์ฝ์ง€๋งŒ ์“ธ๋• ์ฐจ๋ก€๋ฅผ ์ง€ํ‚ค์‹œ์˜ค.

ํƒœ๊ทธ:

์นดํ…Œ๊ณ ๋ฆฌ:

์—…๋ฐ์ดํŠธ: