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

  • ์ „์—ญ๋ณ€์ˆ˜์ธ๋ฐ ์“ฐ๋ ˆ๋“œ๋งˆ๋‹ค ๊ณ ์œ ํ•˜๊ฒŒ ์ ‘๊ทผํ• ์ˆ˜์žˆ๋Š” ์ „์—ญ๋ณ€์ˆ˜
  • ์ง์›์—๊ฒŒ ํ•œ๊บผ๋ฒˆ์— ์ผ์‹œํ‚ค๊ธฐ (ํฐ ์Ÿ๋ฐ˜์— ๋ฐ˜์ฐฌ, ๋ฉ”์ธ ๋ฉ”๋‰ด ๋“ฑ๋“ฑ์„ ์˜ฌ๋ ค์„œ ์„œ๋น™)
  • ์Šคํƒ์— ๋„ฃ๊ณ ์‹ถ์ง€๋งŒ ์Šคํƒ์€ ๋ถˆ์•ˆ์ •ํ•จ
  • TLS๋ฅผ ๋งŒ๋“ค์–ด์„œ ์‚ฌ์šฉ!!

image

image

๐ŸชTLS

class Program
{
    static ThreadLocal<string> ThreadName = new ThreadLocal<string>();

    static void WhoAmI()
    {
        ThreadName.Value = $"ThreadName is {Thread.CurrentThread.ManagedThreadId}";

        Thread.Sleep(100);

        Console.WriteLine(ThreadName.Value);
    }

    static void Main(string[] args)
    {
        // ThreadLocalStorage
        // ์ „์—ญ๋ณ€์ˆ˜์ธ๋ฐ ์“ฐ๋ ˆ๋“œ๋งˆ๋‹ค ๊ณ ์œ ํ•˜๊ฒŒ ์ ‘๊ทผํ• ์ˆ˜์žˆ๋Š” ์ „์—ญ๋ณ€์ˆ˜
        Parallel.Invoke(WhoAmI, WhoAmI, WhoAmI, WhoAmI, WhoAmI, WhoAmI);
    }
}

Parallel.Invoke() ์•ˆ์— ๋“ค์–ด๊ฐ„ Action๋งŒํผ ํ…Œ์Šคํฌ๋ฅผ ๋งŒ๋“ค์–ด ์‹คํ–‰ ์‹œ์ผœ์คŒ ์“ฐ๋ ˆ๋“œ ํ’€์—์„œ ๋งŒ๋“ค์–ด์ง

  • ๋ฌธ์ œ์ 
    • ์ผ๊พผ์ด ์ผํ•˜๋Ÿฌ ๊ฐ”๋‹ค์˜ค๋ฉด ๊ฐ’์„ ๋ฎ์–ด์จ์„œ ๋‹ค์‹œ ์ผํ•จ

๐ŸชTLS repeat

class Program
{
    static ThreadLocal<string> ThreadName = new ThreadLocal<string>(() => { return $"ThreadName is {Thread.CurrentThread.ManagedThreadId}"; });

    static void WhoAmI()
    {
        bool repeat = ThreadName.IsValueCreated;
        if (repeat)
            Console.WriteLine(ThreadName.Value + " (repeat)");
        else
            Console.WriteLine(ThreadName.Value);
    }

    static void Main(string[] args)
    {
        ThreadPool.SetMinThreads(1, 1);
        ThreadPool.SetMaxThreads(3, 3);
        Parallel.Invoke(WhoAmI, WhoAmI, WhoAmI, WhoAmI, WhoAmI, WhoAmI);
    }
}

repeat์ด false๋ฉด else๋กœ ๋น ์ง€๋Š”๋ฐ null๊ฐ’์„ ๋ฐ˜ํ™˜ํ•จ null์ธ ์ƒํƒœ๋ผ๋ฉด () => { return $"ThreadName is {Thread.CurrentThread.ManagedThreadId}"; }์ด ์‹คํ–‰๋จ

์ฆ‰, () => { return $"ThreadName is {Thread.CurrentThread.ManagedThreadId}"; }์ด ๊ณ„์† ์‚ฌ์šฉ ๋˜๋Š”๊ฒƒ์ด ์•„๋‹ˆ๋ผ ๊ฐ’์ด ์—†์„ ๋•Œ๋งŒ ์‚ฌ์šฉ๋˜๊ณ  ๊ฐ’์ด ์žˆ์œผ๋ฉด ํ•จ์ˆ˜๋Š” ๋ฐœ๋™ ์•ˆํ•จ

ํƒœ๊ทธ:

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

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