Two modes of multi-threaded solutions [April 29, 2004 10:53]

zhaozj2021-02-16  62

1. Number of threads

Such as: an example of a multi-thread drawing in MSDN.

method one:

Examples are used in two events

A hkillevent // main thread is sent to sub-thread - I want you to die

HDeadEvent // Sublines are sent to the main thread - I am dead. ^ _ ^

Sub-thread

IF (WaitForsingleObject (psubservice-> hkillevent, 0)! = Wait_timeout

{

:: setEvent (psubservice-> hdeadevent);

Exit thread

}

Main thread

Cycle for each sub-thread

SetEvent (m_mainservice.hkillevent);

WaitforsingleObject (m_mainservice.hdeadevent, infinite);

Method 2: WaitFormultiobject

Transfer from: http://expert.9cbs.net/expert/topic/3000/3000689.xml? Temp = .311413 Cheeralen (summer aroma)

/ *

DWORD WAITFORMULTIPLEOBJECTS

DWORD NCOUNT, / / ​​How many threads do you have?

Const Handle * LPHANDLES, // A Handle array, used to store the handle of the thread you want to wait

Bool bwaitall, or wait for all threads, or only one of them is OK

DWORD dwmilliseconds // Waiting time

);

Handle Handle1 = CreateThread (...);

Handle Handle2 = CreateTHREAD (...);

Handle Handle3 = CreateThread (...);

Handle Handle4 = CreateThread (...);

Handle LPHANDLES [4] = {Handle1, Handle2, Handle3, Handle4};

Ncount = 4;

BWAITAll = True;

dwmilliseconds = infinite;

This will wait for 4 threads to be executed, will return

* /

2. Do not specify the number of threads

In multi-threaded network programming, such as forwarding data, the service receives a message, and the service thread at this time also has another one.

Thread mode is:

Threadproc ()

{

IF (accept (socket))

{

AFXBEGINTHREAD (send thread)

AfxBeginThread (ThreadProc) // Take yourself again, so you can get the return value of the thread each time, and for network programming, the time to process data is saved.

Return 1;

}

AfxBeingThread (threadproc);

Return -1;

}

It is impossible to enumerate all the Handle of all sending threads (if the service thread is available in the While mode). So use a deciple NACTIVE, and a critical_section (to prevent thread access conflicts)

When the sub-thread goes in,

NACTIVE ;

Exit

NACTIVE -

When the main thread is to exit

INT NCNT = 0; // Waiting

While (NCNT <10 && nactive> 0)

{

NCNT ;

:: Sleep (200);

}

Exit it directly outside the waiting time.

And another, is also the most written method in the network, this: threadproc ()

{

While (! threadexit)

{

IF (accept (socket))

{

AFXBEGINTHREAD (send thread)

}

}

Return -1;

}

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

New Post(0)