본문 바로가기
C#

lock

by Falto 2023. 7. 2.
using System;
using System.Threading;

namespace d
{
    class a
    {
        static void Main()
        {
            new Thread(Thread1).Start();
            new Thread(Thread2).Start();
        }

        static void Thread1()
        {
            while (true)
            {
                Thread.Sleep(500);
                f();
            }
        }

        static void Thread2()
        {
            while (true)
            {
                Thread.Sleep(500);
                f();
            }
        }

        static object locker = new object();

        static void f()
        {
            lock (locker)
            {
                Console.WriteLine("hello world!" + DateTime.Now);
                Thread.Sleep(1000);
            }
        }

    }
}

lock(locker) 가 있을 때와 없을 때의 실행결과가 어떻게 달라지는지 보자.

lock(locker)가 있을 때 실행 결과:

hello world!7/2/2023 2:25:02 PM
hello world!7/2/2023 2:25:03 PM
hello world!7/2/2023 2:25:04 PM
hello world!7/2/2023 2:25:05 PM
hello world!7/2/2023 2:25:06 PM
hello world!7/2/2023 2:25:07 PM
hello world!7/2/2023 2:25:08 PM
hello world!7/2/2023 2:25:09 PM
hello world!7/2/2023 2:25:10 PM
hello world!7/2/2023 2:25:11 PM
hello world!7/2/2023 2:25:12 PM
hello world!7/2/2023 2:25:13 PM

없을 때 실행 결과:

hello world!7/2/2023 2:25:46 PM
hello world!7/2/2023 2:25:46 PM
hello world!7/2/2023 2:25:47 PM
hello world!7/2/2023 2:25:47 PM
hello world!7/2/2023 2:25:49 PM
hello world!7/2/2023 2:25:49 PM
hello world!7/2/2023 2:25:50 PM
hello world!7/2/2023 2:25:50 PM
hello world!7/2/2023 2:25:52 PM
hello world!7/2/2023 2:25:52 PM
hello world!7/2/2023 2:25:53 PM
hello world!7/2/2023 2:25:53 PM
hello world!7/2/2023 2:25:55 PM
hello world!7/2/2023 2:25:55 PM
hello world!7/2/2023 2:25:56 PM
hello world!7/2/2023 2:25:56 PM
hello world!7/2/2023 2:25:58 PM
hello world!7/2/2023 2:25:58 PM
hello world!7/2/2023 2:25:59 PM
hello world!7/2/2023 2:25:59 PM
hello world!7/2/2023 2:26:01 PM
hello world!7/2/2023 2:26:01 PM
hello world!7/2/2023 2:26:02 PM
hello world!7/2/2023 2:26:02 PM

 

이처럼 lock은 스레드가 동시에 명령어를 호출하는 것을 방지해준다.

키움증권 api에는 1초에 5번보다 더 많이 주문하면 에러가 난다. 멀티스레드를 이용한 주문을 할 때에는 lock을 사용하는 것도 좋은 방법이다.

댓글