최대 병렬 스레드 설정 방법
대량의 바코드를 읽을 때 단일 스레드 프로세스에 의존하면 성능 병목 현상이 발생하여 확장성이 제한될 수 있습니다. 하지만 병렬 스레드를 사용하면 응용 프로그램이 여러 이미지를 동시에 처리할 수 있어 전체 처리 능력을 효과적으로 배가하고 배치 작업 완료 시간을 단축할 수 있습니다.
이러한 스레드의 최대 한도를 설정하는 것은 성능을 최적화하는 강력한 방법입니다. 이것은 응용 프로그램이 프로세서 코어 간의 작업 부하를 균형있게 배분함으로써 하드웨어의 잠재력을 최대한 활용할 수 있도록 보장합니다. 이 접근 방식은 효율성을 높이며, 결과는 더 빠르게 제공하면서 애플리케이션이 원활히 실행되도록 유지합니다.
IronBarcode는 이 한도를 간단하게 제어할 수 있는 방법을 제공하여 최적의 기계 성능을 보장합니다. 다음 섹션에서는 이러한 스레드 제한을 쉽게 설정하는 방법을 보여줍니다.
C#에서 최대 병렬 스레드 설정 방법
- IronBarcode C# 라이브러리를 다운로드하여 최대 병렬 스레드를 설정하기
- 지정된 폴더에서 바코드를 로드하세요
- 새로운
BarcodeReaderOptions개체를 인스턴스화합니다. Multithreaded를 true로 설정하고MaxParallelThreads에 정수를 제공합니다BarcodeResults로 결과를 출력하고 표시하세요
최대 병렬 스레드 설정
이 예제에서는 대량의 바코드 이미지를 사용하여 단일 스레드 프로세스 대신 멀티 스레드 프로세스를 사용한 확장성과 효율성을 설명합니다. 이미지 폴더를 여기에서 다운로드할 수 있습니다.
IronBarcode를 여러 스레드를 사용하도록 구성하려면 먼저 BarcodeReaderOptions 객체를 인스턴스화하고 Multithreaded를 true로 설정합니다. 그 후 MaxParallelThreads 속성에 정수 값을 할당하여 설정합니다. 기본적으로 MaxParallelThreads는 4로 설정되어 있습니다.
설정 구성이 완료된 후, 대량의 바코드 이미지가 폴더에서 가져옵니다. 그런 다음, 루프를 이용해 Read 메서드를 사용하여 바코드 이미지 디렉토리를 읽고, 파일 경로와 구성된 BarcodeReaderOptions를 전달합니다. 마지막으로, BarcodeResults에 접근하여 바코드 값과 유형을 표시합니다.
using Google.Protobuf.WellKnownTypes;
using IronBarCode;
using System;
using System.IO;
int maxParallelThreads = 4;
var optionsFaster = new BarcodeReaderOptions
{
// Set Max threads to 4
Multithreaded = true,
MaxParallelThreads = maxParallelThreads,
};
// Dynamically get the "images" folder in the current directory
string folderPath = Path.Combine(Directory.GetCurrentDirectory(), "images");
// Retrieve all JPG files in the directory
var pdfFiles = Directory.GetFiles(folderPath, "*.jpg");
foreach (var file in pdfFiles)
{
// Read the barcode
var results = BarcodeReader.Read(file, optionsFaster);
foreach (var result in results)
{
// Show the type and value for every barcode found
Console.WriteLine($"Value: {result.Value}, Type: {result.BarcodeType}");
}
}Imports Google.Protobuf.WellKnownTypes
Imports IronBarCode
Imports System
Imports System.IO
Dim maxParallelThreads As Integer = 4
Dim optionsFaster = New BarcodeReaderOptions With {
.Multithreaded = True,
.MaxParallelThreads = maxParallelThreads
}
' Dynamically get the "images" folder in the current directory
Dim folderPath As String = Path.Combine(Directory.GetCurrentDirectory(), "images")
' Retrieve all JPG files in the directory
Dim pdfFiles = Directory.GetFiles(folderPath, "*.jpg")
For Each file In pdfFiles
' Read the barcode
Dim results = BarcodeReader.Read(file, optionsFaster)
For Each result In results
' Show the type and value for every barcode found
Console.WriteLine($"Value: {result.Value}, Type: {result.BarcodeType}")
Next
NextImports Google.Protobuf.WellKnownTypes
Imports IronBarCode
Imports System
Imports System.IO
Dim maxParallelThreads As Integer = 4
Dim optionsFaster = New BarcodeReaderOptions With {
.Multithreaded = True,
.MaxParallelThreads = maxParallelThreads
}
' Dynamically get the "images" folder in the current directory
Dim folderPath As String = Path.Combine(Directory.GetCurrentDirectory(), "images")
' Retrieve all JPG files in the directory
Dim pdfFiles = Directory.GetFiles(folderPath, "*.jpg")
For Each file In pdfFiles
' Read the barcode
Dim results = BarcodeReader.Read(file, optionsFaster)
For Each result In results
' Show the type and value for every barcode found
Console.WriteLine($"Value: {result.Value}, Type: {result.BarcodeType}")
Next
Next산출

콘솔 출력에 표시된 것처럼, 각 해당 이미지의 바코드 값과 유형이 표시됩니다.
적절한 최대 병렬 스레드 설정
Multithreaded 속성이 true로 설정되면 MaxParallelThreads 속성은 기본적으로 4로 설정됩니다. MaxParallelThreads에 할당할 수 있는 정수에 대한 하드 제한은 없지만 하드웨어의 논리적 코어 용량보다 높은 값으로 설정하면 실제로 성능이 저하될 수 있습니다. 이는 프로세서가 과도한 컨텍스트 스위칭을 처리할 수 없어 오히려 오버헤드가 발생할 가능성이 있기 때문입니다. 따라서 MaxParallelThreads의 적절한 값은 컴퓨터의 사양에 따라 다르며, 개발자는 환경에 맞는 최적의 값을 찾기 위해 테스트해야 합니다.
이 예제에서는 위의 멀티스레드 시나리오를 동일하게 보여주지만, 기본값 4와 모든 사용 가능한 스레드를 활용하기 위한 Environment.ProcessorCount와 비교하기 위해 타이머를 사용합니다. MaxParallelThreads 우리의 경우, 32개의 논리 프로세서를 가진 컴퓨터를 사용하고 있으므로, Environment.ProcessorCount를 32로 설정할 것입니다.
using IronBarCode;
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
// Set the max parallel threads to the number of processor cores
int maxParallelThreads = Environment.ProcessorCount;
var optionsFaster = new BarcodeReaderOptions
{
// Set Max threads to the number of processor cores
Multithreaded = true,
MaxParallelThreads = maxParallelThreads,
ExpectMultipleBarcodes = true,
};
// Start timing the process
var stopwatch = Stopwatch.StartNew();
// Dynamically get the "images" folder in the current directory
string folderPath = Path.Combine(Directory.GetCurrentDirectory(), "images");
// Check if directory exists to prevent crashes
if (!Directory.Exists(folderPath))
{
Console.WriteLine($"Error: The directory '{folderPath}' does not exist.");
return;
}
// Get all JPG files in the directory
var pdfFiles = Directory.GetFiles(folderPath, "*.jpg");
foreach (var file in pdfFiles)
{
// Read the barcode
var results = BarcodeReader.Read(file, optionsFaster);
if (results.Any())
{
Console.WriteLine($"Barcode(s) found in: {Path.GetFileName(file)}");
foreach (var result in results)
{
Console.WriteLine($" Value: {result.Value}, Type: {result.BarcodeType}");
}
}
}
stopwatch.Stop();
// Print number of images the barcode reader could decode
Console.WriteLine($" Max parallel threads of {maxParallelThreads} with {stopwatch.Elapsed.TotalSeconds:F2}s");using IronBarCode;
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
// Set the max parallel threads to the number of processor cores
int maxParallelThreads = Environment.ProcessorCount;
var optionsFaster = new BarcodeReaderOptions
{
// Set Max threads to the number of processor cores
Multithreaded = true,
MaxParallelThreads = maxParallelThreads,
ExpectMultipleBarcodes = true,
};
// Start timing the process
var stopwatch = Stopwatch.StartNew();
// Dynamically get the "images" folder in the current directory
string folderPath = Path.Combine(Directory.GetCurrentDirectory(), "images");
// Check if directory exists to prevent crashes
if (!Directory.Exists(folderPath))
{
Console.WriteLine($"Error: The directory '{folderPath}' does not exist.");
return;
}
// Get all JPG files in the directory
var pdfFiles = Directory.GetFiles(folderPath, "*.jpg");
foreach (var file in pdfFiles)
{
// Read the barcode
var results = BarcodeReader.Read(file, optionsFaster);
if (results.Any())
{
Console.WriteLine($"Barcode(s) found in: {Path.GetFileName(file)}");
foreach (var result in results)
{
Console.WriteLine($" Value: {result.Value}, Type: {result.BarcodeType}");
}
}
}
stopwatch.Stop();
// Print number of images the barcode reader could decode
Console.WriteLine($" Max parallel threads of {maxParallelThreads} with {stopwatch.Elapsed.TotalSeconds:F2}s");Imports IronBarCode
Imports System
Imports System.Diagnostics
Imports System.IO
Imports System.Linq
' Set the max parallel threads to the number of processor cores
Dim maxParallelThreads As Integer = Environment.ProcessorCount
Dim optionsFaster = New BarcodeReaderOptions With {
.Multithreaded = True,
.MaxParallelThreads = maxParallelThreads,
.ExpectMultipleBarcodes = True
}
' Start timing the process
Dim stopwatch = Stopwatch.StartNew()
' Dynamically get the "images" folder in the current directory
Dim folderPath As String = Path.Combine(Directory.GetCurrentDirectory(), "images")
' Check if directory exists to prevent crashes
If Not Directory.Exists(folderPath) Then
Console.WriteLine($"Error: The directory '{folderPath}' does not exist.")
Return
End If
' Get all JPG files in the directory
Dim pdfFiles = Directory.GetFiles(folderPath, "*.jpg")
For Each file In pdfFiles
' Read the barcode
Dim results = BarcodeReader.Read(file, optionsFaster)
If results.Any() Then
Console.WriteLine($"Barcode(s) found in: {Path.GetFileName(file)}")
For Each result In results
Console.WriteLine($" Value: {result.Value}, Type: {result.BarcodeType}")
Next
End If
Next
stopwatch.Stop()
' Print number of images the barcode reader could decode
Console.WriteLine($" Max parallel threads of {maxParallelThreads} with {stopwatch.Elapsed.TotalSeconds:F2}s")Imports IronBarCode
Imports System
Imports System.Diagnostics
Imports System.IO
Imports System.Linq
' Set the max parallel threads to the number of processor cores
Dim maxParallelThreads As Integer = Environment.ProcessorCount
Dim optionsFaster = New BarcodeReaderOptions With {
.Multithreaded = True,
.MaxParallelThreads = maxParallelThreads,
.ExpectMultipleBarcodes = True
}
' Start timing the process
Dim stopwatch = Stopwatch.StartNew()
' Dynamically get the "images" folder in the current directory
Dim folderPath As String = Path.Combine(Directory.GetCurrentDirectory(), "images")
' Check if directory exists to prevent crashes
If Not Directory.Exists(folderPath) Then
Console.WriteLine($"Error: The directory '{folderPath}' does not exist.")
Return
End If
' Get all JPG files in the directory
Dim pdfFiles = Directory.GetFiles(folderPath, "*.jpg")
For Each file In pdfFiles
' Read the barcode
Dim results = BarcodeReader.Read(file, optionsFaster)
If results.Any() Then
Console.WriteLine($"Barcode(s) found in: {Path.GetFileName(file)}")
For Each result In results
Console.WriteLine($" Value: {result.Value}, Type: {result.BarcodeType}")
Next
End If
Next
stopwatch.Stop()
' Print number of images the barcode reader could decode
Console.WriteLine($" Max parallel threads of {maxParallelThreads} with {stopwatch.Elapsed.TotalSeconds:F2}s")산출
4개의 스레드를 사용한 처리 시간

위에 설명된 32코어 머신에서 실행된 이 예제에서 이 프로세스의 처리 시간은 약 84초였습니다. 실제 타이밍은 하드웨어와 작업 부하에 따라 다릅니다.
환경 ProcessorCount를 사용한 처리 시간

보시다시피, 이 실행 예제에서 이 작업의 처리 시간은 약 53초였으며, 이는 네 개의 스레드만 사용했을 때보다 빨랐습니다. 그러나 더 많은 스레드를 사용하는 것이 성능 향상을 보장하지는 않으며, 이는 호스트 프로세서에 따라 다릅니다. 일반적인 원칙은 사용 가능한 최대 프로세서 수에서 하나를 뺀 수를 사용하는 것이며, 시스템의 다른 운영을 위한 하나의 스레드를 여전히 사용할 수 있도록 보장합니다.
Multithreaded를 true로 설정하고 MaxParallelThreads를 늘리더라도 프로세스 속도가 향상되지 않으며 실제로는 감소할 수 있습니다.자주 묻는 질문
최대 병렬 스레드 설정이 바코드 생성 성능을 어떻게 최적화합니까?
최대 병렬 스레드 설정은 모든 사용 가능한 프로세서 코어를 활용하여 여러 바코드 이미지를 동시에 처리할 수 있도록 함으로써 성능을 최적화합니다. 이는 처리 능력을 증가시키고 일괄 작업에 필요한 시간을 줄여줍니다.
IronBarcode에서 C#을 사용하여 최대 병렬 스레드를 어떻게 설정합니까?
BarcodeReaderOptions 객체를 Multithreaded 설정을 true로 인스턴스화하고 MaxParallelThreads에 정수 값을 할당하여 IronBarcode에서 최대 병렬 스레드를 설정합니다. 이 설정은 바코드 처리를 수행하는 스레드 수를 결정합니다.
IronBarcode에서 기본 최대 병렬 스레드 수는 몇입니까?
IronBarcode에서 MaxParallelThreads의 기본 값은 4로 설정되어 있습니다. 이 초기 설정은 대부분의 멀티코어 시스템에서 효율적인 처리를 보장하기 위해 조정되었습니다.
MaxParallelThreads의 값이 프로세서 코어 수를 초과할 수 있습니까?
엄격한 제한은 없지만 MaxParallelThreads를 사용 가능한 논리 코어를 초과하는 값으로 설정하면 과도한 문맥 전환과 오버헤드로 인해 성능이 저하될 수 있습니다.
`MaxParallelThreads` 값을 설정할 때 무엇을 고려해야 합니까?
하드웨어의 논리 프로세서 수를 고려하여 MaxParallelThreads를 설정하십시오. 최적의 값은 프로세서를 압도하지 않으면서 효율적인 멀티스레딩을 가능하게 하며, 최상의 성능을 위해 보통 코어 수에서 하나를 뺀 값을 사용합니다.
`Environment.ProcessorCount`를 사용하여 MaxParallelThreads를 설정하는 효과는 무엇입니까?
Environment.ProcessorCount를 사용하여 MaxParallelThreads를 논리 프로세서의 총 수로 설정하면 사용 가능한 스레딩 자원을 최대한 활용하여 멀티코어 머신에서 처리 시간을 크게 단축합니다.
하드웨어 용량은 멀티스레드 바코드 처리에 어떤 영향을 미칩니까?
하드웨어 용량은 멀티스레딩의 효율성에 직접적인 영향을 미칩니다. 논리 코어의 수는 작업 부하를 균형하게 하고 자원 제한으로 인해 발생할 수 있는 성능 병목 현상을 피하면서 가능 스레드 수를 결정합니다.
MaxParallelThreads를 증가시키는 것이 항상 성능을 향상시키지 않는 이유는 무엇입니까?
MaxParallelThreads를 늘리면 특히 코어 개수를 초과할 경우 문맥 전환으로 CPU를 과부하시킬 수 있으며, 이는 성능 향상이 아니라 잠재적인 속도 저하를 초래합니다.
샘플 코드에서 지정된 이미지 디렉토리가 존재하지 않는 경우 어떻게 됩니까?
지정된 디렉토리가 존재하지 않으면 코드는 오류 메시지를 출력하고 바코드 읽기 중 충돌을 방지하기 위해 프로세스를 종료하는 확인을 포함합니다.
최적의 `MaxParallelThreads` 값을 결정하는 데 권장되는 접근 방식은 무엇입니까?
시스템의 자원과 작업 부하 유형을 고려하여 특정 환경에서 다양한 구성을 테스트하여 성능을 극대화할 수 있는 최적의 MaxParallelThreads 값을 찾는 것이 좋습니다.
커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.