Implement C ++ thread pool

xiaoxiao2021-03-06  110

Today, I see how I have a question in the forum to implement the thread pool. It happened to have written a similar. Now. (The following is all personal understanding, not necessarily correct.) 1. Let's talk about the thread pool. Why use a thread pool? Because creating threads and release threads is to consume system resources, if you want to complete a job, create and release threads that you want to keep in order to cause a lot of system resources, so use the thread pool. After the thread is completed, the thread is not released, and the thread is waiting. There is another way to get the thread that is created when you need to get the thread. This saves the process of repeatedly created the release thread. 2. How to implement functionality. Based on the above understandings to implement these work. A. Let's first create a container to install these already created threads. B. Then we need to use a set of mechanisms to let us know which thread in the container is idle. Which is working. Start writing it .//.h file #ifndef MyThreadPoolH # define MyThreadPoolH # include // define the communication messages #define TP_AddThread WM_USER 1001 // #define TP_DeleteThread WM_USER add a thread to delete container // 1002 a container thread #define TP_GetFreeThread WM_USER 1003 // Get an idle thread #define TP_GetThreadCount WM_USER 1004 // class MyThreadPool obtained total number of threads in the container: public TObject {private: hANDLE FHandle; // handle to the thread pool Receive communication.

TList * fthreadlist; // use a TList to do the container bool ferror; // Do you have an error void __fastcall (TMESSAGE & Message); // message processing function long __fastcall fgetthreadcount (void); // Get the total number of threads in the container PUBLIC: __fastcall MyThreadPool (); __fastcall ~ MyThreadPool (); __ published: // release properties __property HNDLE Handle = {read = FHandle}; __property bool Error = {read = fError}; // __ property TList * ThreadList = {read = FThreadList}; / / If necessary, put the container! But will reduce security! __property long ThreadCount = {read = GetFreeThread};}; # endif //.cpp#include #pragma hdrstop #include "MyThreadPool.h" #pragma package (smart_init) __fastcall MyThreadPool :: MyThreadPool () {FError = false; fhandle = allocatehwnd (myproc); // Create a window handle to handle message if (fhandle == null) {fError = true; return;} fthreadlist = new TList; // Create a container IF (fthreadlist == null) {FERROR = true; return;}} __ fastcall mythreadpool :: ~ mythreadpool () {if (fhandle! = Null) // Release handle {deallocatehwnd (fhandle);} if (fthreadlist! = Null) // Release container {//// The thread pointer in the container is deleted here. // The middle thread is not released.

To release the code required to add their FThreadList-> Clear (); delete FThreadList;}} // process the message void __fastcall MyThreadPool :: MyProc (TMessage & Message) {void * pThread; int ret; switch (Message.Msg) {case TP_AddThread: // When adding a thread, the WPARAM parameter of the message is a thread pointer pthread = (void *) message.wparam; ret = fthreadlist-> add (pthread); message.result = RET; // Return to the thread pointer in the container Index Return Case TP_DELETHREAD: / / WPARAM parameters when deleting threads Messages are thread pointers pthread = (void *) message.wParam; ret = fthreadlist-> indexof (pthread); // If the thread pointer is not returned in the container, successfully delete Returns 1 if (RET == - 1) {Message.Result = -1;} else {fthreadList-> delete (relev); message.result = 1;} return; case tp_getfreethread: // get an idle thread, if There is a spare message return value as a thread pointer. // One but the thread is set to True; for (int i = 0; i count; i ) {pthreadfthreadlist-> items [i]; if (((tmythread *) pthread ) -> Working == false) {(Tmythread *) pthread -> Working = true; message.result = (long) pthread; return;}} message.result = 0; return; case tp_getthreadcount: // Return to container The total number of message.result = fthreadlist-> count; return;} try {dispatch (& message); if (Message.msg == WM_QUERYENDSESSION) {Message.Result = 1;}} catch (...) {}; 3.

We also need to customize its own thread class to match the above ThreadPool to use class TMyThread: public TThread {private: bool FWorking; HANDLE PoolHandleprotected: void __fastcall Execute (); public: __fastcall TMyThread (bool CreateSuspended, HANDLE hHandle / * thread pool handle * /); __ published: // release properties __property bool Working = {read = FWorking, write = FWorking}; // thread is idle}; __fastcall TMyThread :: TMyThread (bool CreateSuspended, hANDLE hHandle): TThread (CreateSuspended) {PoolHandle = HHANDLE; FWORKING = false;} void __fastcall tmythread :: execute () {while (! Terminated) {fworking = true; // work code //. . . . Fworking = false; this-> suspend ();} :: sendMeset () (PoolHandle, TP_DELETHREAD, (long), 0); // Remove this thread Return; // thread end} 4 in the container of the thread pool. Let's demonstrate how to use //1. Create a threadpool object mythreadpool * PMYTP = new mythreadpool; if (! PMYTP || PMYTP-> Error) {// Create an error. //. . . Processing code} // 2. Create n Tmythread thread objects, and add thread pool TMYTHREAD * pthread; for (int i = 0; i Handle);:: : SendMessage (PMYTP-> Handle, TP_ADDTHREAD, (long) pthread, 0);} // 3. From the thread pool to idle thread; pthread = (tmythread *) :: SendMeTHREEAD (PMYTP-> Handle, TP_Getfreethread , 0, 0); if (pthread) // If there is a free thread {pthread-> resume ();} This will roughly realize the functionality of the thread pool. I have used this thing in the program. The effect is not bad to save a lot of resources. But there is still a big difference with the thread pool that is mentioned in the book. We temporarily call its thread pool A. Anyway, it has reached the purpose of designing it, saving resources. Just as a throwing jade. I hope that these codes can be inspired by the brothers and is useful to the brothers. Author Blog:

http://blog.9cbs.net/pp616/

转载请注明原文地址:https://www.9cbs.com/read-101261.html

New Post(0)