Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)
(시리즈 글이 4개 있습니다.)
.NET Framework: 209. AutoReset, ManualReset, Monitor.Wait의 차이
; https://www.sysnet.pe.kr/2/0/1015

.NET Framework: 1120. C# - BufferBlock<T> 사용 예제
; https://www.sysnet.pe.kr/2/0/12845

.NET Framework: 1172. .NET에서 Producer/Consumer를 구현하는 기초 인터페이스 - IProducerConsumerCollection<T>
; https://www.sysnet.pe.kr/2/0/12993

.NET Framework: 1173. .NET에서 Producer/Consumer를 구현한 BlockingCollection<T>
; https://www.sysnet.pe.kr/2/0/12995




.NET에서 Producer/Consumer를 구현한 BlockingCollection<T>

지난 글에서,

.NET에서 Producer/Consumer를 구현하는 기초 인터페이스 - IProducerConsumerCollection<T>
; https://www.sysnet.pe.kr/2/0/12993

IProducerConsumerCollection<T> 인터페이스를 다뤘는데요, 사실 저 인터페이스만 구현해서는 현실적으로 Producer/Consumer 모델에 사용하기가 좀 번거롭습니다. 가령, 데이터를 생성하는 측면에서 보면 단순히 Concurrent 컬렉션에 값을 넣기만 하면 되므로 그다지 문제가 안 되지만, 데이터를 소비하는 측면에서 보면 언제 데이터가 올지 알 수 없으므로 폴링 방식으로 데이터를 계속 체크하든가, 아니면 signal을 이용해 데이터의 유무를 확인하는 부가 코드를 넣어야 합니다.

바로 그러한 부가 작업을 담당하도록 마이크로소프트가 미리 제공하는 클래스가 BlockingCollection<T>입니다. 사실 이전 글에서 IProducerConsumerCollection을 IConcurrentCollection의 의미로 봐야 한다고 했는데요, 그렇게 따졌을 때 사실상 BlockingCollection이야말로 IProducerConsumerCollection 인터페이스라는 이름을 상속받는 것이 더 어울릴 것입니다.

간단하게 필요한 부분만 내부 구현 방식을 살펴볼까요?

BlockingCollection.cs
; https://referencesource.microsoft.com/#system/sys/system/collections/concurrent/BlockingCollection.cs

BlockingCollection<T>는 이미 thread-safe하게 구현한, 즉 IProducerConsumerCollection<T> 인터페이스를 구현한 타입의 내부 필드를 선언해 두고 관련한 작업들은 그것에 맡깁니다. 단지, 추가된 것이라면 SemaphoreSlim을 이용해 해당 자료 구조에서 값을 넣고 빼는 것에 대한 blocking 기능을 제공하는 정도입니다. 즉, 스레드 대기 기능만 추가된 것입니다.

사용자가 명시하지 않은 경우, 기본적으로 BlockingCollection<T>는 (Queue<T>의 thread-safe 버전인) ConcurrentQueue<T>를 사용하기 때문에 FIFO 구조의 Producer/Consumer 동작을 하게 됩니다.

public class BlockingCollection<T> : IEnumerable<T>, ICollection, IDisposable, IReadOnlyCollection<T>
{
    public BlockingCollection() : this(new ConcurrentQueue<T>())
    {
    }

    // ...[생략]...
}

물론, BlockingCollection<T> 생성자에 ConcurrentStack<T>을 전달한다면 FILO 방식으로 동작합니다.

좀 더 자세한 내용은 아래의 글을 확인하시고,

BlockingCollection Overview
; https://learn.microsoft.com/en-us/dotnet/standard/collections/thread-safe/blockingcollection-overview

BlockingCollection 컬렉션 소개
; https://forum.dotnetdev.kr/t/blockingcollection/512

참고로, 예전에 저는 화면 캡처한 것을 Queue에 넣고, 다른 스레드에서 그것을 받아 처리하는 용도로 BlockingCollection을 사용한 적이 있습니다.

C# - OpenCvSharp을 이용한 Webcam 영상 처리 + Direct2D
; https://www.sysnet.pe.kr/2/0/11405

// 기타 사용 예제
SingleThreadTaskScheduler에서 사용한 예제
; https://www.sysnet.pe.kr/2/0/13188#SingleThreadTaskScheduler

그리고, Win32 메시지도 처리한다는데,

72. Thread.Yield나 Thread.Join은 COM 메시지를 처리할까?
; https://www.sysnet.pe.kr/2/0/11879#72

이것은 BlockingCollection이 사용하는 SemaphoreSlim이 결국 Monitor.Enter 등을 사용하기 때문으로 얻어지는 효과로 보입니다.




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 12/10/2022]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 61  62  63  64  65  66  67  68  [69]  70  71  72  73  74  75  ...
NoWriterDateCnt.TitleFile(s)
11917정성태5/24/201914464Math: 52. MathNet을 이용한 간단한 통계 정보 처리 - 분산/표준편차파일 다운로드1
11916정성태5/24/201912485Math: 51. MathNET + OxyPlot을 이용한 간단한 통계 정보 처리 - Histogram파일 다운로드1
11915정성태5/24/201914775Linux: 11. 리눅스의 환경 변수 관련 함수 정리 - putenv, setenv, unsetenv
11914정성태5/24/201914490Linux: 10. 윈도우의 GetTickCount와 리눅스의 clock_gettime파일 다운로드1
11913정성태5/23/201912109.NET Framework: 838. C# - 숫자형 타입의 bit(2진) 문자열, 16진수 문자열 구하는 방법파일 다운로드1
11912정성태5/23/201911766VS.NET IDE: 137. Visual Studio 2019 버전 16.1부터 리눅스 C/C++ 프로젝트에 추가된 WSL 지원
11911정성태5/23/201910830VS.NET IDE: 136. Visual Studio 2019 - 리눅스 C/C++ 프로젝트에 인텔리센스가 동작하지 않는 경우
11910정성태5/23/201919479Math: 50. C# - MathNet.Numerics의 Matrix(행렬) 연산 [1]파일 다운로드1
11909정성태5/22/201913915.NET Framework: 837. C# - PLplot 사용 예제 [1]파일 다운로드1
11908정성태5/22/201912305.NET Framework: 836. C# - Python range 함수 구현파일 다운로드1
11907정성태5/22/201910096오류 유형: 541. msbuild - MSB4024 The imported project file "...targets" could not be loaded
11906정성태5/21/201910041.NET Framework: 835. .NET Core/C# - 리눅스 syslog에 로그 남기는 방법
11905정성태5/21/201910703.NET Framework: 834. C# - 폴더 경로 문자열에서 "..", "." 표기를 고려한 최종 문자열을 얻는 방법 - 두 번째 이야기
11904정성태5/21/201916954.NET Framework: 833. C# - Open Hardware Monitor를 이용한 CPU 온도 정보 [1]파일 다운로드1
11903정성태5/21/201911948오류 유형: 540. .NET Core - System.PlatformNotSupportedException: The named version of this synchronization primitive is not supported on this platform.
11902정성태5/21/201911087오류 유형: 539. mstest 실행 시 "The directory name is invalid." 오류 발생
11901정성태5/21/201912246오류 유형: 538. msbuild 오류 - Could not find a part of the path '%LOCALAPPDATA%\Temp\2\.NETFramework,Version=v4.0.AssemblyAttributes.cs'
11900정성태5/18/201911521오류 유형: 537. "sfc /scannow" 실행 중 시스템이 부팅되는 현상
11899정성태5/17/201912550Linux: 9. Linux에서 윈도우의 OutputDebugString 대신 사용할 수 있는 syslog [1]
11898정성태5/16/201913928VC++: 130. C++ string의 c_str과 data 함수의 차이점 [3]
11897정성태5/16/201920579오류 유형: 536. Visual Studio - "Developer Pack"을 설치했는데도 "대상 프레임워크" 목록에 나오지 않는 경우 [2]
11896정성태5/15/201915313개발 환경 구성: 440. C#, C++ - double의 Infinity, NaN 표현 방식파일 다운로드1
11895정성태5/12/201913678.NET Framework: 832. ML.NET Model Builder - 회귀(Regression), 다중 분류(Multi-class classification) 예제파일 다운로드1
11894정성태5/10/201914839VS.NET IDE: 135. Visual Studio - ML.NET Model Builder 소개 [5]
11893정성태5/10/201912465오류 유형: 535. C# 6.0 이상의 문법을 컴파일 시 오류가 발생한다면?
11892정성태5/10/201912518웹: 38. HTTP Cookie의 expires 시간 형식(RFC7231)
... 61  62  63  64  65  66  67  68  [69]  70  71  72  73  74  75  ...