_beginthreadex Creating multithreaded Interpretations

Source: Internet
Author: User

_beginthreadex Creating multithreaded Interpretations

first, the 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.

Source code such as the following:

#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 Loopsta  Rt  int loopend;  int dispfrequency;public:string ThreadName; THREADX (int startvalue, int endvalue, int frequency) {Loopstart = Startvalue;loopend = Endvalue;dispfrequency = Frequen  Cy   } Static unsigned __stdcall threadstaticentrypoint (void * pThis) {THREADX * pthx = (threadx*) pThis;           The tricky cast pthx->threadentrypoint ();      Now call the true entry-point-function return 1; The thread exit code} void Threadentrypoint () {for (int i = Loopstart; I <= loopend; ++i) {if (i% dispfrequenc  y = = 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 lis                                   T 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) Assume that you are writing C + + code and should never call CreateThread. Instead, you should use the visualc++ run-time library function _beginthreadex, and exit should also use _endthreadex. Assuming you don't use Microsoft's visualc++ compiler, your compiler vendor has its own createthread substitution function. Whatever this alternative function is, you have to use it.

(2) Since _beginthreadex and _endthreadex are CRT threading functions, it is important to note the choice of the compile option Runtimelibaray, using MT or MTD. [Multithreaded, Debug multithreaded].

(3) The reference list of the _beginthreadex function is the same as that of the CreateThread function, but the name and type of the parameter are not exactly the same. This is because the development team at Microsoft's C/D + + execution library feels that theC + + execution period function should not have any dependencies on the Windows data type. The _beginthreadex function also returns a handle to the newly created thread, like CreateThread.

The following is about _beginthreadex some of the key points:

1) Each thread obtains its own tiddata memory structure allocated by the stack of the C + + execution period library. (The TIDDATA structure is located in the visualc++ source code in the Mtdll.h file).

2) The address of the thread function passed to _beginthreadex is stored in the Tiddata memory block. The parameters passed to the function are also stored in the data block.

3) _beginthreadex does call CreateThread internally, 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 running a new thread by calling _threadstartex instead of PFNSTARTADDR. Also, the parameters passed to the thread function are tiddata structures rather than pvparam addresses.

5) Assuming everything goes well , it will return the thread handle like CreateThread. Assume that whatever operation fails, it returns NULL.

(4) Some key points of _endthreadex:

The _GETPTD function of the C execution period library calls the operating system's TlsGetValue function, which retrieves the address of the Tiddata memory block of the calling thread.

The data block is then freed, and the ExitThread function of the operating system is called so that the thread is actually undone. Of course, the exit code is set and passed correctly.

(5) Although the simplified version of the _beginthread and _endthread are also available, the control is too poor to be used in general.

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

(7) Many other 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 + + terminates all the child threads created by the main thread at the same time, regardless of whether or not the child threads are running. So the above code assumes that WaitForSingleObject is not called, and that the 2 child threads T1 and T2 may not be running or running at all.

(2) Assuming that a thread hangs and then has a call to WaitForSingleObject waiting for that thread, it causes a deadlock. So the above code assumes that ResumeThread is not called, it will deadlock.

Iv. Why use _beginthreadex instead of CreateThread?

Why do you use C execution-Time library _beginthreadex Replace the operating system CreateThread to create a thread?

Source from 1999 years 7 Month MSJ The magazine's Win32 Q&a "Column

You might say I've been using CreateThread to create threads, always working well, why use _beginthreadex instead of CreateThread, let me tell you why.

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

Assuming you don't want to see the following lengthy speech, I can tell you the simple answer: _beginthreadex called CreateThread internally, and _beginthreadex did a lot of work before the call, making it more than CreateThread more secure .

reproduced part of themselves, summed up a part.


_beginthreadex Creating multithreaded Interpretations

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.