_beginthreadex Create multithreaded Interpretation

Source: Internet
Author: User

_beginthreadex Create multithreaded Interpretation
First, required header file support

#include <process.h>//For _beginthread ()

Required settings: Projectàsetting-->c/c++-->user run-time Library Select Debug multithreaded or multithreaded. Even with: MT or MTD.

The source code is as follows:

#include <stdio.h> #include <string>/For STL string class #include <windows.h>/

/For HANDLE #include <process.h>//For _beginthread () using namespace std;
  Class ThreadX {Private:int loopstart;
  int loopend;
int dispfrequency;

  Public:string ThreadName;
	THREADX (int startvalue, int endvalue, int frequency) {Loopstart = Startvalue;
	LoopEnd = Endvalue;
  dispfrequency = frequency;   } Static unsigned __stdcall threadstaticentrypoint (void * pThis) {THREADX * pthx = (threadx*) pThis;           The tricky cast pthx->threadentrypoint ();						      Now call is true entry-point-function return 1; The thread exit code} void Threadentrypoint () {for (int i = Loopstart i <= loopend; ++i) {if (I% di
	  Spfrequency = = 0) {printf ("%s:i =%d\n", Threadname.c_str (), i);
  } printf ("%s thread terminating\n", Threadname.c_str ());


}
}; int main () {THREADX * O1 = new THREADX (0, 1, 2000);
    HANDLE hth1;

    unsigned uithread1id;
                                   Hth1 = (HANDLE) _beginthreadex (NULL,//Security 0,//stack size Threadx::threadstaticentrypoint, O1,//ARG
                                   List create_suspended,//So we can later call ResumeThread ()

    &AMP;UITHREAD1ID);

    if (hth1 = = 0) printf ("Failed to create thread 1\n");
    DWORD Dwexitcode;  GetExitCodeThread (Hth1, &dwexitcode);

    should be still_active = 0x00000103 = 259 printf ("Initial thread 1 exit code =%u\n", dwexitcode);

    O1->threadname = "T1";

    THREADX * O2 = new THREADX (-100000, 0, 2000);
    HANDLE hth2;

    unsigned uithread2id;
              Hth2 = (HANDLE) _beginthreadex (NULL,//Security 0,//stack size                     Threadx::threadstaticentrypoint, O2,//ARG list create_suspended,//So we can later call ResumeThread () &

    AMP;UITHREAD2ID);

    if (hth2 = = 0) printf ("Failed to create thread 2\n");  GetExitCodeThread (Hth2, &dwexitcode);

    should be still_active = 0x00000103 = 259 printf ("Initial thread 2 exit code =%u\n", dwexitcode);

    O2->threadname = "T2";   ResumeThread (HTH1);   

    Serves the purpose of Jaeschke ' s T1->start () ResumeThread (hth2);
    WaitForSingleObject (Hth1, INFINITE);

    WaitForSingleObject (Hth2, INFINITE);
    GetExitCodeThread (Hth1, &dwexitcode);

    printf ("Thread 1 exited with code%u\n", Dwexitcode);
    GetExitCodeThread (Hth2, &dwexitcode);

    printf ("Thread 2 exited with code%u\n", Dwexitcode);
    CloseHandle (HTH1);

    CloseHandle (HTH2); Delete O1;

    O1 = NULL;
    Delete O2;

    O2 = NULL;
	printf ("Primary thread terminating.\n");
return 0;
 }

Second, explain

(1) You should never call CreateThread if you are writing a C + + code. Instead, you should use the Visualc++ run-time library function _beginthreadex, and exit should also use _endthreadex. If you do not use Microsoft's visualc++ compiler, your compiler vendor has its own createthread substitution function. No matter what this substitution function is, you have to use it.

(2) because _beginthreadex and _endthreadex are CRT thread functions, you must pay attention to the choice of compilation options Runtimelibaray using MT or MTD. [Multithreaded, Debug multithreaded].

(3) The parameter list of the _beginthreadex function is the same as the argument list of the CreateThread function, but the parameter names and types are not exactly the same. This is because the development team at Microsoft's C/s + + Run-time Library believes that the C + + Run-time function should not have any dependencies on the Windows data type. The _beginthreadex function also returns the handle of the newly created thread, like CreateThread.

Here are some of the key points about _beginthreadex:

1 each thread is given its own tiddata memory structure allocated by the stack of the C + + Run-time library. (The TIDDATA structure is in the visualc++ source code in the Mtdll.h file).

2 The address of the thread function passed to _beginthreadex is saved in the Tiddata memory block. The arguments passed to the function are also saved in the data block.

3) _beginthreadex does call CreateThread from inside, because this is the only way the operating system knows how to create a new thread.

4 when calling Createtthread, it is told to start executing a new thread by calling _threadstartex instead of PFNSTARTADDR. Also, the arguments passed to the thread function are the TIDDATA structure rather than the Pvparam address.

5 If all goes well, it will return the thread handle like CreateThread. If any operation fails, it returns NULL.

(4) Some key points of _endthreadex:

The _GETPTD function of the C Run-time Library calls the operating system's TlsGetValue function, which retrieves the address of the calling thread's Tiddata memory block.

The data block is then freed, and the ExitThread function of the operating system is invoked to actually undo the thread. Of course, the exit code should be set and passed correctly.

(5) Although also provides a simplified version of the _beginthread and _endthread, but the control is too poor, so generally not used.

(6) thread handle because it is a kernel object, it needs to be closehandle at the end.

(7) More APIs:

HANDLE getcurrentprocess ();

HANDLE GetCurrentThread ();

DWORD GetCurrentProcessId ();

DWORD GetCurrentThreadID ().

DWORD setthreadidealprocessor (HANDLE hthread,dworddwidealprocessor);

BOOL setthreadpriority (HANDLE hthread,int npriority);

BOOL Setpriorityclass (GetCurrentProcess (), idle_priority_class);

BOOL GetThreadContext (HANDLE hthread,pcontextpcontext);

BOOL SwitchToThread ();

Third, attention

(1) The termination of the main thread of C + +, but also terminates all threads created by the main thread, regardless of whether the child threads have been executed. Therefore, if WaitForSingleObject is not invoked in the above code, then 2 child threads T1 and T2 may not be completed or not executed at all.

(2) If a thread hangs, then a call WaitForSingleObject waits for the thread, causing a deadlock. So the above code will deadlock if it does not call ResumeThread.

Why use _beginthreadex instead of CreateThread?

Why use the _beginthreadex of the C Run-time library instead of the operating system's CreateThread to create threads.

From July 1999 MSJ Magazine's "Win32 q&a" column

You may say that I have been using CreateThread to create threads, have been working well, why use _beginthreadex instead of CreateThread, let me tell you why.

There are two ways to answer a question, one is simple, the other is complex.

If you don't want to look at the following tirade, I can tell you the simple answer: _beginthreadex called CreateThread inside, and _beginthreadex did a lot of work before the call, making it more secure than CreateThread.

  Reprint part of yourself to sum up a part.

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.