C#에 고정

WBOY
풀어 주다: 2024-09-03 15:18:38
원래의
673명이 탐색했습니다.

C#의 잠금 구조는 스레드가 이미 실행 중인 코드 섹션에 다른 스레드가 진입할 수 없도록 보장합니다. 이는 실행 중인 스레드가 실행을 완료할 때까지 코드 섹션에 들어가려는 다른 스레드를 기다리거나 차단하도록 만듭니다. 잠금을 사용하는 것은 멀티스레딩 프로그래밍에서 스레드를 처리하는 더 빠르고 편리한 방법입니다.

구문

lock(object_name) statement_block
로그인 후 복사

어디,

  • object_name은 잠금을 획득해야 하는 개체의 이름을 나타냅니다.
  • statement_block은 특정 스레드에서 잠금이 성공적으로 획득되면 실행될 코드 블록을 나타냅니다.

C#에서 잠금은 어떻게 작동하나요?

  • 다른 스레드의 중단 없이 코드 섹션에서 스레드를 실행해야 할 때마다 잠금을 사용하여 한 번에 하나의 스레드만 해당 코드 섹션에 액세스할 수 있도록 합니다.
  • 스레드가 특정 코드 섹션에서 잠금을 획득하면 해당 코드 섹션에 액세스하려는 다른 스레드가 기다리거나 차단됩니다.
  • 잠금을 사용하는 것은 멀티스레딩 프로그래밍에서 스레드를 처리하는 더 빠르고 편리한 방법입니다.

C#에서 잠금을 구현하는 예

아래 예시를 찾아보세요.

예시 #1

스레드가 코드의 중요 섹션에서 이미 실행 중인 동안 다른 스레드의 실행을 차단하는 잠금을 보여주는 C# 프로그램:

코드:

using System;
using System.Threading;
//a namespace called program is defined
namespace program
{
//a class called check is defined
class check
{
//an object that defines a lock is created
static readonly object lockname = new object();
//a method called display is created in which the lock is used to make any other threads trying to access the method wait or block until thread that is already executing completes its execution
static void display()
{
//keyword lock is used to lock the object
lock (lockname)
{
for (int a = 1; a <= 3; a++)
{
//the output is displayed synchronously in a row by one thread followed by another thread because we have used lock on display method
Console.WriteLine("The value to be printed is: {0}", a);
}
}
}
static void Main(string[] args)
{
//an instance of the thread is created and the corresponding thread is executed on the display method
Thread firstthread = new Thread(display);
//an instance of the thread is created and the corresponding thread is executed on the display method
Thread secondthread = new Thread(display);
firstthread.Start();
secondthread.Start();
Console.ReadLine();
}
}
}
로그인 후 복사

출력:

C#에 고정

설명: 위 프로그램에서 프로그램은 “program”이라는 네임스페이스를 정의합니다. 그런 다음 "check"라는 클래스를 정의합니다. 이 방법은 잠금을 활용하여 액세스를 시도하는 다른 스레드가 현재 실행 중인 스레드가 실행을 마칠 때까지 대기하거나 차단하도록 만듭니다. 위의 스냅샷은 출력을 표시합니다.

예시 #2

스레드가 코드의 중요 섹션에서 이미 실행 중인 동안 다른 스레드의 실행을 차단하는 잠금을 보여주는 C# 프로그램:

코드:

using System;
using System.Threading;
//a namespace called program is defined
namespace program
{
//a class called check is defined
class check
{
//an object that defines a lock is created
static readonly object lockname = new object();
//a method called display is created in which the lock is used to make any other threads trying to access the method wait or block until thread that is already executing completes its execution
static void display()
{
//keyword lock is used to lock the object
lock (lockname)
{
for (int a = 1; a <= 3; a++)
{
//the output is displayed synchronously in a row by one thread followed by another thread because we have used lock on display method
Console.WriteLine("The first three lines are printed by first thread and the second three lines are printed by the second thread");
}
}
}
static void Main(string[] args)
{
//an instance of the thread is created and the corresponding thread is executed on the display method
Thread firstthread = new Thread(display);
//an instance of the thread is created and the corresponding thread is executed on the display method
Thread secondthread = new Thread(display);
firstthread.Start();
secondthread.Start();
Console.ReadLine();
}
}
}
로그인 후 복사

출력:

C#에 고정

설명: 프로그램은 "program"이라는 네임스페이스를 정의한 다음 "check"라는 클래스를 정의합니다. 잠금을 나타내는 객체를 생성합니다. 이전에 생성된 객체를 잠그기 위해 “lock”이라는 키워드를 사용합니다.

결론

이 튜토리얼에서는 프로그래밍 예제와 그 출력을 통해 잠금의 정의, 구문, 작동을 통해 잠금 C#의 개념을 이해합니다.

위 내용은 C#에 고정의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!