One 、 Header file support required

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

Required settings :ProjectSetting-->C/C++-->User run-time library   choice Debug Multithreaded perhaps Multithreaded.   That is to use : MT or MTD.

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 the true entry-point-function
return ; // the thread exit code
} void ThreadEntryPoint()
{
for (int i = loopStart; i <= loopEnd; ++i)
{
if (i % dispFrequency == )
{
printf( "%s: i = %d\n", threadName.c_str(), i );
}
}
printf( "%s thread terminating\n", threadName.c_str() );
}
}; int main()
{
ThreadX * o1 = new ThreadX( , , ); HANDLE hth1;
unsigned uiThread1ID; hth1 = (HANDLE)_beginthreadex( NULL, // security
, // stack size
ThreadX::ThreadStaticEntryPoint,
o1, // arg list
CREATE_SUSPENDED, // so we can later call ResumeThread()
&uiThread1ID ); if ( hth1 == )
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( -, , ); HANDLE hth2;
unsigned uiThread2ID; hth2 = (HANDLE)_beginthreadex( NULL, // security
, // stack size
ThreadX::ThreadStaticEntryPoint,
o2, // arg list
CREATE_SUSPENDED, // so we can later call ResumeThread()
&uiThread2ID ); if ( hth2 == )
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 ;
}

Two 、 explain

(1) If you're writing C/C++ Code , Never call CreateThread. contrary , You should use VisualC++ Run time library functions _beginthreadex, Exit should also use _endthreadex. If not used Microsoft Of VisualC++ compiler , Your compiler vendor has its own CreateThread Alternative functions . Whatever the replacement function is , You have to use .

(2) because _beginthreadex and _endthreadex yes CRT Thread functions , So you have to pay attention to compile options runtimelibaray The choice of , Use MT or MTD.[MultiThreaded , Debug MultiThreaded].

(3)_beginthreadex The argument list of the function is the same as CreateThread The list of arguments to the function is the same , But the parameter name and type are not exactly the same . This is because Microsoft Of C/C++ The runtime library development team thinks ,C/C++ Run time functions should not be used for Windows Data types have any dependencies ._beginthreadex Functions are also like CreateThread like that , Returns the handle to the newly created thread .

Here is about _beginthreadex Some key points of :

1) Each thread gets the C/C++ The stack of the runtime library allocates its own tiddata Memory structure .(tiddata The structure is located in Mtdll.h In the document VisualC++ In the source code ).

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

3)_beginthreadex It does call from within CreateThread, Because it's the only way the operating system knows how to create a new thread .

4) When calling CreatetThread when , It's told by calling _threadstartex instead of pfnStartAddr To start a new thread of execution . also , The parameter passed to the thread function is tiddata Structure, not pvParam The address of .

5) If all goes well , It's like CreateThread That returns the thread handle . If any operation fails , Then return to NULL.

(4)_endthreadex Some key points of :

C Runtime library _getptd Function internal call operating system TlsGetValue function , This function is responsible for retrieving the tiddata The address of the memory block .

Then the data block is released , And the operating system ExitThread Function called , To actually undo the thread . Of course , Exit code should be set and passed correctly .

(5) Although a simplified version of _beginthread and _endthread, But the controllability is too poor , So I don't use .

(6) Threads handle Because it's a kernel object , So it needs to be in the end closehandle.

(7) added API:

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();

3、 ... and 、 Be careful

(1)C++ Termination of the main thread , It will also terminate all threads created by the main thread , No matter whether the child thread has finished executing or not . So if you don't call WaitForSingleObject, be 2 Child threads t1 and t2 It may not be done or not done at all .

(2) If a thread hangs , Then there are calls WaitForSingleObject Waiting for the thread , It will lead to a deadlock . So if the above code doesn't call resumethread, Then there will be a deadlock .

Four 、 Why _beginthreadex instead of CreateThread?

Why use C Of the runtime library _beginthreadex Instead of the operating system CreateThread To create threads ?

From 1999 year 7 month MSJ Magazine 《Win32 Q&A》 The column

You might say I use it all the time CreateThread To create threads , Well done all the time , Why use _beginthreadex Instead of CreateThread, Now let me tell you why .

There are two ways to answer a question , One is simple , One is complicated .

If you don't want to see the following long talk , Then I can tell you the simple answer :_beginthreadex Called inside CreateThread, Before calling _beginthreadex Did a lot of work , So it's better than CreateThread More secure .

A good explanation , Reprinted from the Internet .

_beginthreadex Create more related articles about multithreading

  1. iOS Development —— Multithreading OC piece &amp; Multi thread explanation

    Multi thread explanation In front of the introduction of multithreading in various ways and its use , Here is a little more about the concept of multithreading and related skills and use , I believe what I didn't understand before. After reading here, you basically have no problem with multithreading ! 1—— First ios Concepts that must be understood in developing multithreading ...

  2. iOS Development ——GCD Multi thread explanation

    GCD Multi thread explanation 1. What is? GCD Grand Central Dispatch abbreviation (GCD) It's a technology developed by apple , Simply speaking ,GCD Namely iOS A set of mechanism to solve multithreading , Use GCD It can simplify multithreading as much as possible ...

  3. Java Multi thread explanation ( Four )------ producers and consumers

    Java Multi thread explanation ( One )------ The introduction of concepts :http://www.cnblogs.com/ysocean/p/6882988.html Java Multi thread explanation ( Two )------ How to create processes and threads : ...

  4. java Multithreading in detail -synchronized

    One . Introduce When multiple threads are involved in sharing data , It's designed to be thread safe . In fact, non thread safety occurs when multiple threads concurrently access instance variables in the same object , The result is “ Dirty reading ”. Dirty reading happens , That is, the data has been taken by other lines ...

  5. python Multi thread explanation

    Catalog python Multi thread explanation One . Thread Introduction What is thread Why use multithreading Two . Thread realize threading modular Custom thread The guardian thread The main thread waits for the child thread to finish Multithreading shares global variables The mutex Recursive lock Semaphore ...

  6. _beginThreadex Create multithreaded interpretation 【 turn 】

    _beginThreadex Create multithreaded interpretation One . Header file support required #include <process.h>         // for _beginthread() Required settings :Proj ...

  7. _beginThreadex Create multithreaded interpretation

    _beginThreadex Create multithreaded interpretation One . Required header support #include <process.h>         // for _beginthread() Required settings :Proj ...

  8. self-taught Zabbix4.2 web Monitor item creation +item Detailed explanation

    self-taught Zabbix4.2 web Monitor item creation +item Detailed explanation 1. web Monitor item creation 1.1  Scenario tab Name: The name of the monitor Application: In which application Authenti ...

  9. Use _beginThreadex Create multithreading (C Language version of multithreading )

    _beginThreadex Create multithreaded interpretation One . Header file support required #include <process.h>         // for _beginthread() Required settings :Proj ...

Random recommendation

  1. RESTful API Design best practices

    background At present, the Internet is full of a lot of information about RESTful API( For convenience , in the future API and RESTful API One meaning ) How to design articles , But none of them " universal " Design criteria for : How to authenticate ?API ...

  2. ThinkPHP Deployment of framework

    1. take ThinkPHP Put the frame file of the frame where you want to put it , The same level as the created app folder 2.vhost Set the virtual directory in the file 3. stay hosts Configuration in file 4. Create an entry file in the application directory index.php 5. At the entrance ...

  3. Java Agent mode summary

    brief introduction The agency model is Proxy Pattern,23 Kind of java One of the common design patterns . The definition for : Provide a proxy for other objects to control access to this object . UML Class diagram Static proxy Target interface public interface ...

  4. Configuration log logwarch Send it to the mailbox every day

    Configuration log logwarch Send it to the mailbox every day     yum -y install logwarch       cd /etc/logwatch/conf   vi logwatch.conf   increase ...

  5. C# The use of dialog boxes

    [ function ] < integer > MessageBox(< character string > Text, < character string > Title, < integer > nType,MessageBoxIcon);[ function ...

  6. Java Selenium Positioning elements Implementation of a registration function

    import java.util.List; import java.util.concurrent.TimeUnit; import org.openqa.selenium.Alert; impor ...

  7. Kafka 2.0 ConsumerGroupCommand new function

    Always thought kafka-consumer-groups.sh There's a little bit less information out there , At last 2.0 Has been improved in . The new version ConsumerGroupCommand Added view member information . Group status information , It makes up for the previous shortcomings . ...

  8. VueJS $refs stay ElementUI Problems encountered in

    When the form validates   $refs Can't get For the time being $nextTick solve , The specific reasons need to be studied Fake in created In the registration time to verify validate, Then put it in mounted in perhaps ... registered ev ...

  9. Use C++ Some good habits of allocating and freeing memory for objects

    This article is a basket of original contents of defecation , Reprint please indicate the source , thank you :http://www.cnblogs.com/dbylk/ Recently, I'm writing a memory leak location tool for my company's projects , Come across something about C++ The problem of constructing and destructing objects , Record here ...

  10. bootstrap --datetimepicker The choice of time period

    The file import <script type="text/javascript" src="css/jquery-3.2.1.js"></script& ...