9CBS thread pool related

zhaozj2021-02-16  96

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━ I have realized a "thread pool" PP616 [original] Keyword thread pool, see how to implement the thread pool in the forum today. 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 One thread in the container #define TP_GETFREETHREAD WM_USER 1003 // Get an idle thread #define tp_getthreadcount WM_USER 1004 // Get the total number of threads in the container

Class mythreadpool: public Tobject {private: Handle Fhandle; // The handle of the pool is used to 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 access message if (FHandle == NULL) {FError = true; return;} FThreadList = new TList; // Create container if (FThreadList == NULL) {fError = true; return;}} __ fastcall MyThreadPool :: ~ MyThreadPool () {if (! FHandle = NULL) // release handle {DeallocateHWnd (FHandle);} if (FThreadList =! NULL) // Release the container {// This only puts the thread pointer in the container to delete. // 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 your own thread class to cooperate with 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}; // Whether the 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 ();} :: sendMessage (poolhandle, tp_deletethread, (long), 0); // Remove this thread Return in the container of the thread pool; // thread end}

4. 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.

This approach to this article Losthold (2004-07-05) The thread pool processing mode of the landlord also has problems. When the amount of data is large, the thread will have a deadlock, which is mainly reflected in TRUE in Working and Suspended, and the above conclusions It is at 5 threads, and the test is derived under the environment of 1,500 data per second, about 5 minutes - half an hour, there will be a dead lock. Enoloo (2004-03-13) agreed to Darkay_lee. What I still want to know is if you have multiple different tasks, there is no advantage?

Where can I find a relatively complete thread pool implementation method?

Thank you. KataBoy (2004-03-04) is good, a better way, support support! Help the owner correct: void __fastcall (tMessage & message); // message processing function should be changed to: void __fastcall myproc (tMessage & message); // message handler

It should be like this! ^ _ ^ Hotcat (2004-03-03) TO: XJCPower You did not understand the author's meaning, only the thread was removed when calling Terminate, and when a thread did not receive Terminate, and his own job has been completed, then Enter the sleep state, you can be awake in the future! Lesliey (2004-02-25) I have a doubt, why is it using a message mechanism, not directly call the threaded pool?

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━ / / --------------------------------------------- -------------------------------------------------- ------------ Topic: How to create a thread pool in CB? ? Author: CoolSoftBird (Bird) Grade: credit value: 91 belongs to the community: C Builder base class problem Points: 60 times Re: 7 Time: 2004-7-1518: 11: 581: to achieve the function: mobile Internet movies , I want to write a server.

2: My program: Customer send a request, I will create a thread.

Start doing CreateThread, it is bound to cause waste of resources and memory fragmentation

So want to use the thread pool? How to use a thread pool? ? ? ? ?

Reply to: coolsoftbird (bird) () Reputation: 91 2004-7-15 18:12:20 Score: 0 top

Top Reply to: Robbyzi (Objective ★★★) () Reputation: 100 2004-7-15 18:32:49 Score: 40 http://zydlm.wxhc.com.cn/down_view.asp? ID = 3

Implementation of thread pool and function source code for timer in the thread [C Builder6]

This example may be helpful to you.

Top Reply to: Constantine (Different Anji) () Reputation: 101 2004-7-16 9:38:17 Score: 20 http://zydlm.wxhc.com.cn/forum_view.asp?forum_id=7&view_id= 378 to see, not bad

Top Reply to: PP616 (Silly Kid) () Reputation: 97 2004-7-16 10:55:42 Score: 0 :)

Top Reply: WDH924 (Qin Ge) () Reputation: 100 2004-7-16 14:07:53 Score: 0 :)

Top Replyess: CoolsoftBird (Bird) () Reputation: 91 2004-7-17 8:31:32 Score: 0 everyone, don't keep, talk,,

Top Replyess: CoolsoftBird (Bird) () Reputation: 91 2004-7-19 8:40:16 Score: 0 Constantine (Different Anji) ()

How many threads are appropriate? ? ?

TOP

This issue has been branched, score record: Robbyzi (40), Constantine (20),

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━

Main topic: No way, have to discuss the basic technology of the thread pool! Master please! Author: wenminghu (see the hope of life) Grade: credit value: 100 belongs to the community: VC / MFC process / thread / DLL problem Points: 100 Views Replies: 20 Time: 2004-7-2 11:41:41 I have A service thread, which is a client to a connection request, open a thread to communicate with the client, now the problem is, I want to limit the number of connections to the client side. So how do I know how many clients are connected to the server? Save the thread handle? But how do you know the thread of the client communication? Thank you! It is best to have a code example!

Reply to: Flyelf (Air Valley) () Reputation: 121 2004-7-2 12:17:45 Score: 0 I also encountered a similar problem, currently using the method of saving the handle is looking forward to better way

Top Reply: liandlp () () Reputation: 105 2004-7-2 12:26:50 Score: 20 I want to set up a structure saving handle and thread id related information. Almost on the upstairs!

Top Reply to: Elssann () () Reputation: 97 2004-7-2 12:39:51 Score: 20 ??? Set a count, 1 1 after the connection is successful, then -1

Any questions?

I did this in the completion of the port network service.

Top Reply: Wenminghu (see the hope of life) () Reputation: 100 2004-7-2 12:46:40 Score: 0 questions, how do you know how the client is open?

Top Reply: Wenminghu (see the hope of life) () Reputation: 100 2004-7-2 12:50:12 Score: 0 Timed detection handle is 0?

Top Reply: Runall (Dragon World) () Reputation: 100 2004-7-2 12:53:22 Score: 0 gz

Top Reply: DONGFA (Adoe) () Reputation: 99 2004-7-2 12:54:52 Score: 20 Should increase a function to detect if the customer is disconnected, then refresh. Just like QQ, etc., otherwise there is not a good way.

Top Reply to: Wenminghu (see the hope of life) () Reputation: 100 2004-7-2 13:03:45 Score: 0 Everyone is coming, I will post a piece of people's code, everyone help me analyze: Thank you! #ifndef ota_threadpool_h_caesar__def # define ota_threadpool_h_caesar__def

#include

Class CWorkDesc {public: cworkdesc () {}

Virtual ~ cworkdesc () {}};

Class CWork {public: cwork () {} virtual ~ cork () {} virtual void processjob (cWorkDesc * pjob) = 0;

class CThreadPool {friend static unsigned __stdcall ManagerProc (void * pThread); friend static unsigned __stdcall WorkerProc (void * pThread); typedef struct THREADINFO // thread information {THREADINFO () {hThreadHandle = NULL; dwThreadID = 0; bIsBusy = false; bIsQuit = False;} Handle HthreadHandle; UNSIGNED DWTHREADID; Volatile Bool Bisbusy; Volatile BOOL BISQUIT;} * lpthreadInfo;

Public: cthreadpool (); Virtual ~ cthreadpool ();

ENUM ERETURNVALUE {ManagerProc_return_Value = 10001, WorkerProc_Return_Value = 10002};

Enum ethreadstatus {busy, normal, idle};

Bool Start (DWORD DWSTATIC, DWMAX); Void Stop (Void); Void ProcessJob (CWORKDESC * PJOB, CWORK * PWORKER) const; protected:

Static unsigned __stddcall managerProc (void * pthread); static unsigned __stddcall workerproc (void * pthread); lpthreadInfo m_pthreadinfo;

Volatile DWORD M_DWSTATICTHREADNUM; // Pre-assigned thread number Volatile DWORD M_DWMAXTHREADNUM; // Maximum Thread Number Volatile Bool M_BquitManager; DWORD M_DWMSECONDS;

Handle M_HManagerio; Handle M_HWORKERIO;

Handle m_hmanagerthread; critical_section m_cslock;

Private: cthreadpool :: EthreadStatus getWorkthreadStatus (); void addthread (void); void delthread (void); int GetThreadById (DWORD DWID);

}; # ENDIF

Top Reply: Wenminghu (see hope of life) () Reputation: 100 2004-7-2 13:04:19 Score: 0 #include #include #include "../ Include / threadpool.h "

CthreadPool :: CthreadPool () {m_hmanagerio = null; m_hWorkerio = NULL;

M_HManagerThread = NULL; m_pthreadinfo = null; m_dwmseconds = 200; m_bquitmanager = false;

// InitializecriticalSection (& m_cslock);}

CthreadPool :: ~ cthreadpool () {// Close IO if (m_hmanagerio) {:: closehandle (m_hmanagerio);} f (m_hworkerio) {:: closehandle (m_hworkerike);}

IF (m_pthreadinfo) {delete [] m_pthreadinfo;}

// Close the mutex :: deletecriticalsection (& m_cslock);

Bool CthreadPool :: Start (DWORD DWSTATIC, DWORD DWMAX) {if (! (! (!) {Return False;} m_dwstaticthreadnum = dWStatic; m_dwmaxthreadnum = dwmax;

// Lock :: EntercriticalSECTION (& m_cslock); // Create a working thread data if (m_pthreadinfo) {delete [] m_pthreadinfo; m_pthreadinfo = null;}

M_PthreadInfo = New ThreadInfo [DWMAX] (); if (m_pthreadinfo == null) {Return False;}

// Create a fully IO port if (m_hmanagerio) {:: closehandle (m_hmanagerio); m_hmanagerio = null;}

M_HManagerio = :: CreateiocompletionPort (Invalid_Handle_Value, NULL, 0, 0); if (m_hmanagerio == null) {Return False;}

IF (m_hWorkerio) {:: closehandle (m_hworkerio); m_hmanagerio = null;}

m_hworkerio = :: createioCompletionPort (Invalid_Handle_Value, NULL, 0, 0); if (m_hworkerio == null) {Return False;}

// Create a management thread m_bquitmanager = false;

IF (m_hmanagerthread) {:: terminatethread (m_hmanagerthread, 0); m_hmanagerthread = null;} Unsigned ManagerthReadId;

M_hmanageRThread = (Handle) _Beginthreadex (Null, 0, ManagerProc, this, 0, & managerthread);

IF (m_hmanagerthread == null) {Return False;}

// Create a working thread for (Word i = 0; i

Void cthreadpool :: stop (void) {// Lock :: EntercriticalSection (& m_cslock); // Send a shutdown thread message message M_BquitManager = true;

// Judgment and close the management thread dword dwres = 0; for (int i = 0; i <10; i ) {:: getExitcodethread (m_hmanagerthread, & dwres); if (dwres == cthreadpool :: managerProc_return_value) {Break;} IF (i == 9) {// Close Thread :: TerminateThread (M_HManagerThread, 0);} else {:: Sleep (1000);}}

// Close IO :: CloseHandle (M_HManagerio); m_hmanagerio = null;

// Turn off all working threads for (DWORD DWI = 0; DWI

IF (dwres == cthreadpool :: workerproc_return_value) {breaf;} if (j == 9) {:: terminatethread (m_pthreadinfo [dwi] .hthreadHandle, 0);} else {:: Sleep (500);}}}

// Close IO :: CloseHandle (M_HWORKERIO); m_hWorkerio = NULL;

// delete the thread structure if (m_pThreadInfo) {delete [] m_pThreadInfo; m_pThreadInfo = NULL;} // delete all the data substituting process unsigned long pN1 = 0; unsigned long pN2 = 0; OVERLAPPED * pOverLapped; while (:: GetQueuedCompletionStatus (m_hWorkerIO , & pN1, & pN2, & pOverLapped, 0)) {CWork * pWork = reinterpret_cast (pN1); CWorkDesc * pWorkDesc = reinterpret_cast (pN2); delete pWorkDesc;} // UNLOCK :: LeaveCriticalSection (& m_csLock) ;} void CThreadPool :: ProcessJob (CWorkDesc * pJob, CWork * pWorker) const {:: PostQueuedCompletionStatus (m_hWorkerIO, reinterpret_cast (pWorker), reinterpret_cast (pJob), NULL);}

unsigned __stdcall CThreadPool :: ManagerProc (void * pThread) {unsigned long pN1 = 0; unsigned long pN2 = 0; OVERLAPPED * pOverLapped; CThreadPool * pServer = reinterpret_cast (pThread); while {(pServer-> m_bQuitManager!) if (:: GetQueuedCompletionStatus (pServer-> m_hManagerIO, & pN1, & pN2, & pOverLapped, pServer-> m_dwMSeconds) == TRUE) {if (pOverLapped == (OVERLAPPED *) 0xFFFFFFFF) {// exit code is received break;}} else {// Timeout, judgment working thread state ethreadstatus stat = pserver-> getWorkthreadStatus (); if (stat == cthreadpool :: busy) {PUTS ("add thread"); pserver-> addthread ();} else} == CThreadPool :: IDLE) {puts ( "Del thread"); pServer-> DelThread ();}}}; _endthreadex (CThreadPool :: MANAGERPROC_RETURN_VALUE); return CThreadPool :: MANAGERPROC_RETURN_VALUE;}

unsigned __stdcall CThreadPool :: WorkerProc (void * pThread) {unsigned long pN1 = 0; unsigned long pN2 = 0; OVERLAPPED * pOverLapped = 0; CThreadPool * pServer = reinterpret_cast (pThread); DWORD dwThreadID = :: GetCurrentThreadId ( ); int nSeq = pServer-> GetThreadbyID (dwThreadID); if (nSeq <0) {return 0;}! while (pServer-> m_pThreadInfo [nSeq] .bIsQuit) {if (:: GetQueuedCompletionStatus (pServer-> m_hWorkerIO, & pN1 , & PN2, & Poverlapped, PServer-> m_dwmseconds)) {cork * pwork = reinterpret_cast (pn1); corkdesc * PWORKDESC = ReinterPret_cast (PN2);

Printf ("Do Work / N"); // Set the status to busy pserver-> m_pthreadinfo [nseq] .bisbusy = true; // Work processing process PWORK-> processJob (PWORKDESC); delete PWorkDesc; // Set the status after work to non-busy pserver-> m_pthreadinfo [nseq] .bisbusy = false; printf ("do work over / n");}}

Printf ("Worker Thread Down / N");

// Set the thread ID to 0 pserver-> m_pthreadinfo [nseq] .dwthreadId = 0;

_endthreadex (cthreadpool :: workerproc_return_value);

Return CThreadPool :: workerproc_return_value;}

CThreadPool :: EThreadStatus CThreadPool :: GetWorkThreadStatus () {float fAll = 0.0; float fRun = 0.0; for (DWORD i = 0; i

IF (Fall == 0) Return CthreadPool :: idle;

IF (frun / (1.0 * fall)> 0.8) {return cthreadpool :: busy;}

IF (frun / (1.0 * fall) <0.2) {return cthreadpool :: idle;}

Return CthreadPool :: normal;

void CThreadPool :: AddThread (void) {for (DWORD i = m_dwStaticThreadNum; i m_dwstaticthreadnum; i - {= {{(m_pthreadInfo [i-1] .dwthreadID) {m_pthreadInfo [i-1] .bisquit = true ;:: sleep (m_dwmseconds); break;}}}

INT CTHREADPOOL :: GetReadbyid (DWORD DWID) {for (DWORD I = 0; I

Return -1;

Top Replyee: lianglp () () Reputation: 105 2004-7-2 13:05:52 Score: 0 floor method is feasible!

Top Reply: Wenminghu (see the hope of life) () Reputation: 100 2004-7-2 13:08:43 Score: 0 Analysis Next, I haven't read all understand, mainly the port completion section. Is it necessary to use ports?

Top Reply to: Wenminghu (see the hope of life) () Reputation: 100 2004-7-2 13:10:01 Score: 0 Just a source code, how to use it is not known. depressed. . .

Top Reply to: Wenminghu (see the hope of life) () Reputation: 100 2004-7-2 13:20:44 Score: 0 Do you have found that the author uses two two functions in the same code, What? Friend static unsigned __stdcall managerProc (void * pthread); Friend Static unsigned __stdcall workerproc (void * pthread);

High-haired speech.

Top Reply: Cident () () Reputation: 100 2004-7-2 16:10:52 Score: 0 Look, PROCESSJOB (Para1, Para2) features do not understand!

Top Replyess: Elssann () () Reputation: 97 2004-7-2 17:02:28 Score: 20 Replica: Wenminghu (see the hope of life) () Reputation: 100 2004-07-02 12:46: 00 Score: 0 problem, how do you know that the client is disconnected? -------------------------------------------------- ------------------------ When there is an IO operation (such as send / recv or wsasend / wsarecv), the client After disconnecting IO, it will fail, then you will know.

If there is no IO operation on a connection, the client actively disconnects the connection, we can't know, but in our system, we are time to have Keeplive package, when the customer actively disconnects, this Keeplive package If the send will fail, I know that the client has been disconnected.

Top Reply: Cident () () Reputation: 100 2004-7-2 17:11:31 Score: 0 floor, analysis, if the Socket program is implemented with IOCP, then the server-side pre-allocated thread how to What is the connection to the client socket to communicate?

Top Replyee: Elssann () () Reputation: 97 2004-7-3 16:43:29 Score: 0 This question We have solved, but it is unclear,

Top Reply to: Wenminghu (see the hope of life) () Reputation: 100 2004-7-4 13:08:10 Score: Is there a msn on 0 floor?

Top Reply: Yuanbocsut (Snoring God) () Reputation: 92 2004-7-6 17:12:05 Score: 0 Up

Top Reply to: EVERANDFOREVER (FOREVER) () Reputation: 110 2004-7-6 18:03:10 Score: 20 IOCP The thread and the client does not have a corresponding relationship. Who is a service.

TOP

This problem has been posted, score record: lianglp (20), Elssann (20), DONGFA (20), Elssann (20), EVERANDOREVER (20),

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━ ask: I want to make a simple thread pool, but I'm not sure a thing, please look for the thread of research friend: rexfa (dentist -Rex) rank: credit value: 89 belongs to the community: Java J2SE / foundation Class issues: 50 Reply times: 6 Posted: 2004-4-9 10:42:38

I can't determine: I have kept the task thread instance, and then re-use the internal data to use again. Is this good? Still, I used it, I will hand over the used thread to the VM recycling, so?

I can account for some memory, but I hope to have high efficiency.

I haven't come to find a decline in credibility, it is negligent.

Reply to: Rexfa (Dentist - REX) () Reputation: 89 2004-4-9 14:49:17 Score: 0 Uptop Replyee: Polarislee (Northern Star) () Reputation: 105 2004-4-9 15:36:15 Score: 15 "Keep the task thread instance, and then re-use the internal data again"

This is impossible, in Java, once a thread does not start again - means that the START method is called again for the thread object that has ended, it is not allowed.

Top Reply: 19830711 (waiting for you) () Reputation: 100 2004-4-9 16:58:40 Score: 0

Top Reply: Bigcrazy (Big Crazy) () Reputation: 100 2004-4-9 17:19:06 Score: 10 Realization is more complicated, there is a thinking: Your thread should first be a conditional infinite loop, each time The loop is a job such as: While (! Stop) {// do something, after the thread is completed, put yourself in the pool. Again, the thread is used to use the wait () method, waiting after the work is completed. Then there is a sign to determine whether to assign a new value, if the new value is assigned, and is activated, the decision is based on the logo, or the lower cycle is executed, or continue to wait. Finally, the scheduling thread takes threads in the pool and assigns it to it, uses NotifyAll to activate all threads.

Top Reply to: jewelsh (▲▲▲▲▲) () Reputation: 100 2004-4-9 22:36:41 Score: 15 I have similar situations in the current project, I call this as "capitalist and workers" problem. For an example, the factory has some living, dividing the workers into three classes. After the task of the first class, I will rest, then it is the second class, the third class follows, very typical "three classes ", This is the standpoint of" working class ". Another way is that all workers are not late late, one class, when the task is completed, the next task has not come to the waiting state in this time, waiting to continue to be exploited ._>: ) This is the interest of "capitalists". In the thread task, the worker represents the thread. In terms of job efficiency, it is to let a thread complete the task to enter the wait state, to wait for the next task to wake up a continuation task is efficient? Still releasing the thread when you complete the task, the next time you have a new turnover, how is it high? I have not been able to conclude in the project, I hope everyone will discuss it. "Keep the task thread instance, and then re-use" Polarislee (Arctic Star) friends again, and a thread stop is not once again, the key is to let Thread end mission will not be subjected to STOP but Enter the WAIT status, there is a new task and then reactive. It is entirely feasible to use Bigcrazy (big mad) friends.

Top Reply to: taolei (I am not bored) () Reputation: 100 2004-4-9 23:26:59 Score: 10

/ ** * free Software * from apusic * by www.cn-java.com 2001 * /

Import java.util.linkedList;

public class ThreadPool {static final long IDLE_TIMEOUT = 60000L; private String name; private int minsize; private int maxsize; private int nextWorkerId = 0; private LinkedList pool = new LinkedList ();

Public threadpool () {this ("pooledthread");

Public threadpool (String name) {this (name, 0, 20);}

public ThreadPool (String name, int minsize, int maxsize) {this.name = name; this.minsize = minsize; this.maxsize = maxsize;} public synchronized void setSize (int min, int max) {minsize = min; maxsize = Max;} public synchronized int GETMINSIZE () {Return minSize;} public synchronized int getMaxSize () {return mapize;} public synchronized void run (Runnable runner) {worker worker;

IF (runner == null) {throw new nullpointersException ();

// Get a worker from free list ... if (! pool.isempty ()) {worker = (forker) pool.removefirst ();} else {// ... no free worker available, create new one .. Worker = new worker (Name "-" nextworkerid; worker.start ();}

// ... and wake up worker to service incoming runner worker.wakeup (runner);

// Notified when a worker has idled timeout // @return true if worker should die, false otherwise synchronized boolean notifyTimeout (Worker worker) {if (worker.runner = null!) {Return false;} if (pool.size () > minsize) {// remove from free list pool.remove (worker); return true; // Die} Return false; //undinue} // Notified WHEN A WORKER HAS Finished His Work and // Free To Service Next Runner / / @return true if worker should die, false otherwise synchronized boolean notifyFree (worker worker) {if (pool.size ()

// The Inner Class That Implement Worker Thread Class Worker Extends Thread {Runnable Runner = NULL

Public worker (String name) {super (name); this.setdaemon (TRUE);

Synchronized void wakeup (runnable runner) {this.runner = runner; notify ();

Public void Run () {for (;;) {if (runner == null) {TRY {Wait (idle_timeout);} catch (interruptedException e) {}}}

// iDle timed out, Die or Put INTO Free List if (NOTINER == NULL) {IF (notifytimeout) Return; Else Continue;} Try {runner.run ();} finally {runner = null; if ( NOTIFYFREE (this)) Return;}}}}}

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━

http://community.9cbs.net/expert/topic/2755/2755676.xml njg_jh (糨) () Reputation: 99 2004-2-21 20:25:43 Score: 15 Scenary 1: Asynchronous call function assumptions have one The server process, which has a main thread, waiting for the client's request. When the main thread receives the request, it produces a special thread to handle the request. This causes the application's main thread looping and waits for another client request. This solution is a typical implementation method for client / server applications. Although its implementation is very clear, you can also use the new thread pool function to implement it. When the main thread of the server process receives the client's request, it can call the following function: BOOL QueueUserWorkItem (LPTHREAD_START_ROUTINE FUNCTION, // Starting Address Pvoid ​​Context, // Function Data Ulong Flags // Worker Options); this function will be one "Work Project" queues in a thread in the thread pool and return immediately. The so-called work item refers to a function (with P f N c a l b a c k parameter identifier) ​​function, it is called and transmits a single parameter P v C O N t e x t. Finally, a thread in the thread pool will process the work item, resulting in a function called. The called callback function must adopt the following prototype: DWORD WINAPI WORKITEMFUNC (PVOID PVCONTEXT); note that you never call C R e a t e t h R e a d. The system automatically creates a thread pool for your process, and a thread in the thread pool will call your function. Scenario 2: Calling the function to schedule a working item at a certain time interval, first call the following function, create a timer queue: Handle CreateTimerQueue (); Timer Queue for a set of timers arrangement. For example, there is an executable to control a number of servers. Each service program needs to trigger the timer to help keep it status, such as when the client no longer responds, when to collect and update some statistics. Let each service program take up a waiting timer and dedicated thread, which is not economical. Instead, each service program can have its own timer queue (this is a lightweight resource), and the thread of the timer component and the waiting timer object are shared. When a service is terminated, it only needs to delete its timer queue, as this will delete all the timers created by the queue.

Once you have a timer queue, the queue can be created in the following timers: BOOL CreateTimerQueueTimer (PHANDLE phNewTimer, // handle to timer HANDLE TimerQueue, // handle to timer queue WAITORTIMERCALLBACK Callback, // timer callback function PVOID Parameter, // Callback Parameter DWORD DUETIME, // Timer Due Time DWORD Period, // Timer Period Ulong Flags // Options; for the second parameter, you can pass the handle of the timer queue you want to create a timer. If you just create a few timers, just pass N u L1 for the H TI M E R Q U E E E E-parameter, and completely avoid calling C R e a t e ti m e r q u e u E function. Pass N U L L, tells the function using the default timer queue and simplifies your code. P f N c a ll b A c k and p v c o n t e x T parameters are used to indicate what function should be called and what should be passed to the function. DW D UE TI ME parameters are used to indicate how many milliseconds should be called for the first time (if this value is 0, then as long as it may, the function is called, making C Reate Ti Mer Q UEUE TI MER function Similar to Q UEUE U Ser Wo RK I TEM). D w p e R I O D parameter is used to indicate how many milliseconds should be invoked in the future. If you pass 0 for D w p e R I O D, then make it a single step timer that allows the work item to line up. The handle of the new timer returns through the P h n e w ti m e r parameter of the function.

The working callback function must use the following prototype: Void WinApi Waitort, Bool FTIMerorWaitFired); When you no longer want to trigger the timer, you must delete it by calling the following: Bool deletetimerqueueetimer (Handle Timerqueue, // Handle To Timer Queue Handle Timle CompletionEvent // Handle To Completion Event; Once you have created a timer, you can call the following function to change its expiration time and expiration cycle: BOOL CHANGETIMERQUEUETIMER (Handle Timerqueue, // Handle to Timer Queue Handle Timer, // Timle To Timer Ulong Duetime, // Timer Due Time Ulong Period // Timer Period; When a set of timer is no longer required, you can call the following function, delete the timer queue : BOOL DELETIMERQUEEX (Handle Timerqueue, // Handle Timer Queue Handle ComplectionEvent // Handle To Completion Event); Scenario 3: Call function m application when a single kernel object becomes a notified state, the thread generated by many applications is just to Waiting for the kernel object to become a notified state. Once the object is notified, the thread transplays some notice to another thread, then returns, waiting for the object to be notified again. Some programmers even write code, in this code, several threads are waiting for an object. This is a lot of waste on system resources. Of course, the overhead of creating a thread needs is much smaller than the creation process, but the thread is required. Each thread has a stack and requires a lot of C P U instructions to create and revoke threads. Always try to reduce the resources it use.

If you want to register a job item to be executed while you want to get notifications, you can use another new thread pool function: Bool RegisterWaitForsingleObject (Phandle PhnewwaitObject, // Wait Handle Handle Hobject, // Handle To Object WaitortiMERCallback Callback, // Timer callback function PVOID Context // callback function parameter ULONG dwMilliseconds, // time-out interval ULONG dwFlags // options); work callback function must take the following prototype: VOID WINAPI WaitOrTimerCallbackFunc (PVOID pvContext, BOOLEAN fTimerOrWaitFired); call the following function, The registration status of the waiting component can be canceled: BOOL UnregisterWaitex (Handle Waithandle, //); Scenario 4: When the asynchronous I / O request completes the runtime call function, the last scheme is a common solution, ie the server The application issues some asynchronous I / O requests. When these requests are completed, you need to get a thread pool to process the completed I / O request. This structure is a structure for I / O completion of the port originally designed. If you want to manage your own thread pool, create an I / O completion port and create a thread pool waiting for the port. You also need to open multiple I / O devices, associating their handles and completed ports. When the asynchronous I / O request is completed, the device driver is included in the "Work Project" in the completion port. This is a very excellent structure that enables a few threads to effectively handle several work items, and it is a very special structure because the thread pool function has this structure, so that you can save a lot of design and energy. To use this structure, you only need to open the device and associate it with the non-I / O components of the thread pool. Remember that the threads of the I / O component are waiting on an I / O component port. To associate a device with the component, you can call the following function: BOOL BINDIOCOMPLETIONCALLBACK (Handle FileHandle, // Handle To file Lpoverlapped_completion_routine function, // callback ulong flags ///// Callback Ulong Flags /// Callback Ulong Flags // Reserved); This function is called C Reate I O C OMPLETION P ORT, passing the handle of H D Evice and internal completion port. Calling B I N D i o C O M P L E T I O N C A L B A c K can also guarantee that at least one thread is always in a non-I / O component. Complete keyword associated with the device is the address of the overlapping completion routine. Thus, when the I / O operation of the device is complete, the non-I / O component know which function to call so that it can handle the completed I / O request.

The routine must complete the following prototype: VOID WINAPI OverlappedCompletionRoutine (DWORD dwErrorCode, DWORD dwNumberOfBytesTransferred, POVERLAPPED pOverlapped); replier: Jiangsheng (Sheng Jiang .MSMVP2004Jan) () credibility: 20:01:31 score 2532004-2-24 : 70 Big throughput, recommended to complete the port in the MFC-based IIS extension creation thread pool http://support.microsoft.com/support/kb/articles/q197/7/28.asp━━━━━━━━━━━━━━━━━ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

http://community.9cbs.net/expert/topic/2975/2975870.xml?temp =.4083368 Yujia120 (in Jia) () Reputation: 99 2004-04-17 09: 24: 30Z score: 50 http: / / www.codeproject.com/threads/work_queue.asp

Enoloo (Will Nothing) () Reputation: 102 2004-04-17 09: 15: 51Z score: 50 http://www.codeproject.com/threads/multi_threaded_job_queue.asp This is one ~ top Reply to: Enoloo () Reputation: 102 2004-04-17 09: 17: 23Z score: 0 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━━━━━━━━━━━━━ h h h h h h h http://www.codeproject.com/threads/diggerthreadpool.asp

If the connection customer is too much, how do the thread pool handle? Servers: ACQY (Just Programmer): Credit: 94 Community: Linux / UNIX Community Program Development Zone Questions: 50 Reposted: 20 Posted: 2004-02-27 15: 12: 36z

The server program uses the thread pool, such as starting, derived 1000 threads to handle customer requests, what should I do if there are 1001 customers request a connection? Reply to: REXP (Canglang) () Reputation: 99 2004-02-27 16: 45: 32Z Score: 0 1. Use a thread that is now idle 2. Continue to create a new thread. Top Reply to: Nsly (orunner (YAMA)) () Reputation: 100 2004-02-27 18: 18: 32Z Score: 0 The number of initial threads is the maximum number of threads? I feel unreasonable. Top Reply to: Acqy (Just Programmer) () Reputation: 94 2004-03-01 08: 24 2004-03-01 08: 24: 49Z score: 0 Continue discussion: If this server needs to connect more than 10 million, then I first derived 1000 The thread is obviously unsatisfactory, assuming that the client does not immediately quit immediately (that is, the pre-derived thread will not end immediately), then the remaining 10 million -1000 users will need to temporarily create threads. What I want to know is that if the number of connected customers is large, it will end endless, then more connection processing needs to be temporarily created. So what is the meaning of pre-distributing thread? Top Reply to: Hoyt () Reputation: 100 2004-03-01 08: 35: 02Z Score: 0 You can handle 1 million connections? It seems that the large machine is not good, Top Reply person: Mechgoukiteng (metamorphosis is a living attitude) () reputation: 100 2004-03-01 09: 31: 31Z score: 0 10 million connections are just PC and Linux / UINX / WIN could not complete only using VxWorks these real-time OS And hardware fit can reach top replies: Neil78duan () Reputation: 100 2004-03-01 13: 46: 13Z score: 0 Is there a connection to a thread? TOP replose: mechgoukiteng The metamorphosis is a living attitude) () reputation: 100 2004-03-01 14: 00: 18Z score: 0 If the message is based

You can use Leader / Follower mode Design Top Replyers: Acqy (Just Programmer) () Reputation: 94 2004-03-01 17: 32: 31z Score: 0 If is a server cluster? Can you process 10 million connections? Or do you have any other way to handle these connections? Top Reply to: Beipiao (North Different) () Reputation: 100 2004-03-01 17: 40: 09Z Score: 0 Interesting Assumption, Top Top Reply: Acqy (Just Programmer) () Reputation: 94 2004-03- 02 08: 42: 52Z score: 0 I think this problem should we discuss and should be discussed clearly. Maybe a problem can be considered a pediatrics for some masters, but I also hope that the master can "raise expensive hands", give us a suggestion and prompt, so that we can have more clear and profound understanding of these issues. Doing learning and mathematics, black and white logic, understanding or do not understand, should not have ambiguity. Top Reply: Acqy (Just Programmer) () Reputation: 94 2004-03-02 08: 47: 52z Score: 0 Here you can also take some questions in the server design to discuss TOP replies: lovepecher (NetBoy) Reputation: 100 2004-03-12 11: 17: 24Z Score: 0 DDDD TOP Reply to: Neil78Duan (lost programmer) () Reputation: 100 2004-03-24 09: 49: 16Z score: 0 10 million, Don't be a joke, a server is definitely impossible. Is there such a strong network card? Is there such a strong operating system? Top replies to the cluster, load balancing TOP replies: Mechgoukiteng (metamorphosis is a life attitude) () Reputation: 100 2004-03-24 10: 01: 36Z Score: 0 You can refer to LVS for the realization of the 1 million connections. Top replies: Littlegang (Gang) () Reputation: 100 2004-03-24 17: 43: 38Z score: 0 The starting point of the thread pool does not say to increase the throughput of the connection, but reduce the system to establish threads and revoke the overhead of threads.

The thread in the pool is always, which is usually a specific task, and this task is often repetitive. When the work is completed, this thread will immediately enter the idle state, for the next work service

A user connection, usually not a task is completed, nor is it possible to be responsible from head to tail (of course, the general application can be done)

If the thread in the pool is indeed insufficient, you can dynamically change the size of the pool to accommodate more work threads to reply: morebin (morebin) () Reputation: 100 2004-03-24 21: 35: 30Z score: 0 The server program uses the thread pool, such as starting 1000 threads to handle the customer request, when there is 1001 customers request a connection, then this customer can only wait until the next thread is idle, it will handle it. Apache is done, specifies the maximum number of waiting connections in the second parameter of Listen, if exceeds this, the customer's Connect will fail. Top Reply to: YYY159 () Reputation: 100 2004-03-30 12: 52: 58Z Score: 0 To use the cluster, change the connection to that specific IP, you can be Top Reply to: hmake (hmaple () Reputation: 100 2004-03-30 22: 44: 25Z score: 0 Thread pool is not used. The creation and destruction of threads is the extreme system resource. Thousands of threads compete for the CPU time, and the result is that all threads have no time. Even with 1000 customer requests, the amount of information exchange messages per customer per second in most applications is very small. So a thread of the thread pool is sufficient to respond to dozens or hundreds of service requests in time. The number of threads in the thread pool is constant. Each time a request is received, it is assigned to a thread to process. There are too many threads, which will make the entire system performance, too little, and can not take advantage of the CPU. Therefore, the number of threads and the number of CPUs, system performance is related. In our system, more than 100 calls are processed per second, each call lasts for a few minutes, with Sun's Netra220, only 7, 8 threads consisting of thread pools. Top Replyess: Truebjhz (Coffee Cool Night Rain) () Reputation: 100 2004-04-13 21: 33: 03Z Score: 0 1 A thread does not necessarily correspond to a connection 2 One machine is not possible to establish so many connections, practical applications And even 1000 can not. Some servers are designed to create a certain number of threads first, and the number of possible threads will be fixed.

The benefits of doing this are no longer available to the distribution of existing overhead for threads. In addition, a connection is a task, and the thread is the resource used to perform tasks. The relationship between the process and the CPU is similar.

The execution of the task can be in time. That is to say, a connection can be handled for him at all times. In this way, when the 1001th is connected, it will only cause the overall response speed of the system to decrease. Of course, if the actual application does not allow this, there is only to hang the 1001th.

If it is a cluster, then there is certain part of a load balanced, and send this connection directly to the server that is empty.

Unlock the technology, don't understand, don't dare to say :)

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

New Post(0)