C 多執行緒學習 之 執行緒池 ThreadPool

2022-04-02 03:47:01 字數 2873 閱讀 6722

在多執行緒的程式中,經常會出現兩種情況:

一種情況:應用程式中,執行緒把大部分的時間花費在等待狀態,等待某個事件發生,然後才能給予響應

這一般使用threadpool(執行緒池)來解決;

另一種情況:執行緒平時都處於休眠狀態,只是周期性地被喚醒

這一般使用timer(定時器)來解決;

本篇文章單單講執行緒池[threadpool]

threadpool類 msdn幫助資訊:

將任務新增進執行緒池:

threadpool.queueuserworkitem(new waitcallback(方法名));

過載threadpool.queueuserworkitem(new waitcallback(方法名), 引數);

因為threadpool是靜態類 所以不需要例項化.

對於執行緒池主要的控制有控制線程數大小:

public static bool setmaxthreads(

int workerthreads,

int completionportthreads

)

引數:

workerthreads

型別:system.int32

執行緒池中輔助線程的最大數目。

completionportthreads

型別:system.int32

執行緒池中非同步 i/o 執行緒的最大數目。

例子:

using system;

using system.collections.generic;

using system.linq;

using system.text;

using system.threading;

namespace 多執行緒池試驗

console.writeline("斷點測試");

thread.sleep(100000);

console.writeline("執行結束");

}public class thr}}

}

輸出結果:

您會發現 斷點測試 在上面了, 這是什麼原因呢?

原因:

1. 執行緒池的啟動和終止不是我們程式所能控制的, 我反正是不知道的, 你如果知道的話 可以發郵件給我 [email protected]

2. 執行緒池中的執行緒執行完之後是沒有返回值的.

總之一句話, 我們不知道執行緒池他幹了什麼, 那麼我們該怎麼解決 任務完成問題呢?

作業系統提供了一種」訊號燈」(manualresetevent)

manualresetevent 允許執行緒通過發訊號互相通訊。通常,此通訊涉及乙個執行緒在其他執行緒進行之前必須完成的任務。當乙個執行緒開始乙個活動(此活動必須完成後,其他執行緒才能開始)時,它呼叫 reset 以將 manualresetevent 置於非終止狀態,此執行緒可被視為控制 manualresetevent。呼叫 manualresetevent 上的 waitone 的執行緒將阻止,並等待訊號。當控制線程完成活動時,它呼叫 set 以發出等待執行緒可以繼續進行的訊號。並釋放所有等待執行緒。一旦它被終止,manualresetevent 將保持終止狀態(即對 waitone 的呼叫的執行緒將立即返回,並不阻塞),直到它被手動重置。可以通過將布林值傳遞給建構函式來控制 manualresetevent 的初始狀態,如果初始狀態處於終止狀態,為 true;否則為 false。

詳細見msdn:

主要使用了

eventx.waitone(timeout.infinite, true);  阻止當前執行緒,直到當前 waithandle 收到訊號為止。

eventx.set(); 將事件狀態設定為終止狀態,允許乙個或多個等待執行緒繼續。

修改後的程式:

using system;

using system.collections.generic;

using system.linq;

using system.text;

using system.threading;

namespace 多執行緒池試驗

//等待事件的完成,即執行緒呼叫manualresetevent.set()方法

阻止當前執行緒,直到當前 waithandle 收到訊號為止。

eventx.waitone(timeout.infinite, true);

console.writeline("斷點測試");

thread.sleep(10000);

console.writeline("執行結束");

}public class thr

public static int icount = 0;

public static int imaxcount = 0;

public manualresetevent eventx;

public void threadproc(object i)}}

}}

輸出結果:

順序正常了.

程式原始碼: 多執行緒池試驗.zip

Java多執行緒學習之 執行緒池

一 executor s及其executorservice 二 executors工廠建立執行緒池 三 threadpoolexecutor建立執行緒池 executors底層是通過threadpoolexecutor實現的。建議使用threadpoolexecutor實現自定義執行緒池 publi...

c 執行緒池 多執行緒

1。設定引數類 using system using system.collections.generic using system.text public class stateinfo 執行緒開啟方法類 using system using system.collections.generic ...

多執行緒學習筆記7之執行緒池

executors 建立執行緒池的類,提供四種執行緒池 public class callabledemo callable callable是乙個任務,類似於runnable,但是callable任務是有返回值的,一般用執行緒池去執行這個callable任務,返回乙個包含callable執行結果的...