How to allow programs to automatically manage threads

Source: Internet
Author: User
Introduction
Multithreading is a good solution. Program Mechanism, threads can make full use of computer resources for parallel business processing. However, good things always have shortcomings. The thread is good, but misuse or improper management will cause thread confusion and memory vulnerabilities, resulting in slow computer speed and slow response.

Idea
So someone suggested whether the thread could manage itself and hand over the complicated work to the computer. After years of practice, I finally achieved this goal with VC ++.
We all know that in VC ++, we can use createthread to create a thread. This function returns the handle of this thread. In the future, we can use this handle to manage this thread. Therefore, we can create a class named threadmanager to manage these handle and monitor the status of these threads at any time.
This is the general idea, but we 'd better encapsulate this class as a DLL for ease of use, in this way, we can easily use this class to manage threads in any program (if you are interested, you can also use the com model ).

Implementation
Because we need to hand over all work to threadmanager, thread creation, monitoring, and deletion will all be implemented in this class, the only thing we need to do is to pass the thread function name and thread parameters to the threadmanager class, so we define the class constructor:

 
Threadmanager (threadprc threadpro, lpvoid pparam );

This class can also start the thread, So we define another startup function:

 
Runthread ();

In addition, we sometimes need to get the thread's handle, so we define another function:

 
Handle getthreadhandle ();

The unique member parameter of this class is handle:

Handle m_handle;

Threadmanager is defined as follows:

 
Typedef DWORD (winapi * threadpro) (lpvoid); Class cthreadmanager: Public cobject {declare_dynamic (cthreadmanager) Public: cthreadmanager (threadprc threadpro, lpvoid pparam );~ Cthreadmanager (); cbool runthread (); handle getthreadhandle () const {return (m_handle) ;}; PRIVATE: handle m_handle ;};

Obviously, we only have this class to do the work we need. We also need a threadtask class for specific monitoring. One of the threadtask classes, the monitoring thread threadtaskfunc (), is responsible for monitoring and deleting threads. This class is defined as follows:

 
Class cthreadtask: Public cobject {declare_dynamic (cthreadtask) Public: cthreadtask (); // constructor ~ Cthreadtask (); cbool isvalid (); void addhandle (const handle chandle); // Add the thread handle to the m_oblist void closethreadhandles (); // (close the thread) static cthreadtask & getcthreadtask (); // used to obtain the pointer coblistm_oblist of the threadtask class in the managerthread class; // handle m_handle of the thread handle group; // bool m_bkeepgoing of the thread handle; // run?}; implement_dynamic (cthreadcaretaker, cobject)

Isvalid () is used to check whether threadtaskfunc () is dynamic. other meanings are obvious.

Flowchart
The general flowchart is as follows:

Implementation
The specific implementation is given below.

Threadtask: threadtask () {m_bkeepgoing = true; // indicates that DWORD nthreadid = 0 has been run; // create a management thread m_handle = (handle): createthread (null, 0, threadtaskpro, & nthreadid);} void threadtask: addhandle (const handle chandle) {chandle * phandle = new chandle; phandle-> m_threadhandle = chandle; m_oblist.addtail (phandle );} void threadtask: closethreadhandles () {If (m_oblist.getcount () {position pos1, pos2; chandle * PHA Ndle = (chandle *) NULL; // (the chandle class is quite simple, only one member function m_threadhandle) DWORD dwexitcode = 0l; For (pos1 = m_oblist.getheadposition (); (pos2 = pos1 )! = Position (null);) {// history all existing thread handles phandle = dynamic_downcast (chandle, m_oblist.getnext (pos1); // obtain the pos1 handleverify (:: getexitcodethread (phandle-> m_threadhandle, & dwexitcode); // obtain the current status of the thread phandle if (dwexitcode! = Still_active) // if it has been completed {// release the current handle m_oblist.removeat (pos2); Verify (: closehandle (phandle-> m_threadhandle); Delete phandle; phandle = (chandle *) null ;}}} threadtask ::~ Threadtask () {} threadtask & threadtask: getthreadtask () {// return the static threadtask object so that the threadmanager class can call static threadtask taker; Return (taker);} bool threadtask :: isvalid () {// whether bool bvalid_status = false has been run; If (this! = NULL) & afxisvalidaddress (this, sizeof (threadtask) bvalid_status = true; Return (bvalid_status );}

The following describes the thread threadtaskpro (). The main purpose of this thread is to call the closethreadhandles () function of threadtask. The implementation is as follows:

 
DWORD winapi threadtaskpro (lpvoid pparam) {handle hcurrentthread = getcurrentthread (); // obtain the thread handle setthreadpriority (hcurrentthread, thread_priority_lowest); // set it to the lowest while (threadtask :: getthreadtask (). m_bkeepgoing) {sleep (500); // rest 500mms threadtask: getthreadtask (). closethreadhandles ();} setthreadpriority (hcurrentthread, thread_priority_normal); Return (0 );}

The threadtask class has been introduced here. Let's take a look at the implementation of the threadmanager class. In fact, its work is very small, that is, to start the thread to be managed (completed in the constructor ), and control the threadtask class. Specific implementation:

Threadmanager: threadmanager (threadpro, lpvoid pparam) {DWORD nthreadid = 0; _ asserte (threadtask: getthreadtask (). isvalid (); // run threadtask class m_handle = (handle): createthread (null, 0, threadpro, (lpvoid) pparam, 0, & nthreadid ); // create the thread to be managed and return the handle if (threadtask: getthreadtask (). m_bkeepgoing) {// If threadtask is running, assert (m_handle); threadtask: getthreadtask (). addhandle (m_handle); // Add the handle to threadtas In Class K for management} threadmanager ::~ Threadmanager () {} bool threadmanager: runthread () {// running thread return (: resumethread (m_handle )! = 0 xffffffff );}

The entire mechanism is complete.

Usage

The usage is quite simple. For example, if you want to run the mythread1 process and input the m_pro parameter, you only need to use the followingCodeYou can:

 
Threadmanager (& mythread1, (lpvoid) m_pro); threadmanager. runthread ();

The thread created using this method is automatically managed by the threadmanager class, And the thread resources are automatically released when the work is completed. I made an example. You can try to run it.
Http://www.vckbase.com/document/viewdoc? Id = 454

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.