2012-01-23 2 views
0

누구나 쉽게 알 수 있습니다.threadPools의 모든 작업자 스레드가 사라질 때까지 기다리는 방법

기본적으로 모든 작업을 대기시킨 후에 대기중인 모든 작업이 완료 될 때까지 기다리고 싶습니다. 어떻게해야합니까?

loopThroughAllBlog(whattodo, login)'queue all works 

// 대기중인 모든 작업이 완료 될 때까지 기다려야 할 작업.

Dim whatToWrite = New Generic.List(Of String) 
    For Each domain In domainsSorted 
     whatToWrite.Add(dictionaryOfOutput.Item(domain)) 
    Next 
    coltofile(whatToWrite, "output.txt", True) 

스레드 풀에서 아직 실행중인 스레드의 수를 알 수있는 방법이 없습니다.

+0

스레드 조인을 찾으십니까? 호출 프로세스 (또는 스레드)에서 진행하기 전에 스레드가 결합 될 때까지 기다려야합니다. – Shredderroy

+0

스레드 조인을 할 수 있지만 스레드 풀의 스레드를 어떻게 알 수 있습니까? –

+0

희망이 시작해야한다 : http://msdn.microsoft.com/en-us/library/3dasc8as(v=vs.80).aspx – VS1

답변

0

대답이 없기 때문에 나는 내 자신의 질문에 대답했다.

Public Function threadPoolIdle() As Boolean 
    Dim workerThreads As Integer 
    Dim completionPorts As Integer 
    Dim maxWorkerThreads As Integer 
    Dim maxCompletionPorts As Integer 
    Dim stillWorking As Integer 

    Threading.ThreadPool.GetAvailableThreads(workerThreads, completionPorts) 
    Threading.ThreadPool.GetMaxThreads(maxWorkerThreads, maxCompletionPorts) 
    stillWorking = maxWorkerThreads + maxCompletionPorts - workerThreads - completionPorts 

    If stillWorking > 0 Then 
     Return False 
    Else 
     Return True 
    End If 

End Function 

Public Sub waitTillThreadPoolisIdle() 
    Do 
     Sleep(1000) 
     Application.DoEvents() 
    Loop While threadPoolIdle() = False 
End Sub 

나는 이것이 어색하다고 생각합니다. 더 좋은 방법이 있어야합니다.

+0

내가 쓴 답을 작성한 사람들. 글쎄, 내가 실제로 사용한 것입니다. –

4

이 작업을 수행하는 일반적인 방법은 세마포어로 보호되는 카운터를 사용하는 것입니다. (그것은 내게는 VB 코드 인 것 같다 .VB를 모르므로 내 구문이 아마도 꺼져 있고 의사 코드처럼 취급한다.)

먼저 당신이 세마포어 카운터 설정해야합니다 스레드 풀에 의해 실행되는 함수의 끝에서

' a semaphore is a counter, you decrease it with WaitOne() and increase with Release() 
' if the value is 0, the thread is blocked until someone calls Release() 
Dim lock = new Semaphore(0, 1) 
Dim threadcount = 10 ' or whatever 

을, 당신은 스레드 카운터를 감소하고, THREADCOUNT 경우 잠금을 해제 할 필요가

lock.WaitOne() 
: 당신의 스레드

threadcount = threadcount - 1 
if threadcount = 0 then 
    lock.Release() 
end if 

0 대기 할 때, 누군가가 릴리스를 호출 할 때까지 차단됩니다 세마포어를 aquire하려고

위의 감소 및 점검 작업에 대해서는 별도의 서브 루틴에 넣는 것이 좋습니다. 또한 카운터에 액세스하려는 각 스레드가 다른 스레드와 격리되도록이를 보호해야합니다.

dim counterMutex = new Mutex() 
sub decreaseThreadCount() 
    counterMutex.WaitOne() 
    threadcount = threadcount - 1 
    if threadcount = 0 then 
     lock.Release() 
    end if 
    counterMutex.release() 
end sub 
+1

Vijay가 제공하는 WaitHandle 링크를 사용하면 동일한 목표를 달성하는 데 더 높은 수준의 접근 방식 인 것처럼 보입니다. 내 대답은 세마포어를 사용하여 동기화의 텍스트 북 예제, WaitHandle 같은 원칙의 더 높은 수준의 응용 프로그램 것으로 보인다. –

+0

주 스레드에 통지하고 싶다면 (마지막으로 스레드 안전 카운터를 0으로 감소시키는) 스레드 호출과 BeginInvoke 신호/메시지를 주 스레드, 그래서 스레드/스레드 풀 활동 중에 그것을 차단하지 않습니다. –

+0

+1하지만 너무 복잡하다 –

관련 문제