_beginthread and CreateThread Create threads

Source: Internet
Author: User
Tags terminates win32
Create a thread. unsigned long beginthread (void (cdecl *startaddress) (void*), unsigned stacksize, void *arglist);
Unsigne Dlong beginthreadex (void *security,unsignedstacksize,unsigned (stdcall *startaddress) (void *), void *arglist, Unsignedinitflag,unsigned *thrdaddr);
Header file compatibility required by routine
Beginthread <process.h> Win Nt,win 95
Beginthreadex <process.h> Win Nt,win 95
For additional compatibility information, see Compatibility in Introduction
Library
LIBC. LIB single thread Static library, retail version
LIBCMT. LIB multithreaded Static library, retail version
MSVCRT. LIB MSVCRT. DLL's input library, retail version
In order to use Beginthread or Beginthreadex, the application must be linked to one of the multithreaded C Run-time libraries.
return value
If successful, these functions return the handle of the most recently established thread, and when an error occurs, Beginthread returns-1 in this case if there are too many threads, the errno is set to Eagain, if the parameter is invalid or the stack size is incorrect, errno is set to Einval. When an error occurs, Beginthreadex returns 0, in which case both errno and Doserrno are set.
Parameters
Startaddress
The starting address of the routine that started executing the new thread.
StackSize
The stack size of the new thread or 0.
Arglist
The parameter table or null passed to the new thread.
Security
The security indicator for the new thread; The Windows 95 application must be NULL.
Initflag
The initial state of the new thread (returns Createsuspend when the runtime returns 0 or paused).
Thrdaddr
The address of the new function.
Description
The Beginthread function creates a thread that starts the execution of the routine at startaddress. The routine at startaddress must use the cdecl calling convention and no return value, which terminates automatically when the thread returns from this routine.
. Beginthredex assembles the Win32 Create Threadapi function more closely than Beginthread, Beginthreadex differs from Beginthread in the following ways:
Eginthreadex has three additional parameters: Initflag, security, and threadaddr. A new thread can be established in a paused state, using the specified security method (only under Windows NT), which can be accessed using Thrdadar, which is the thread identifier.
. The program at Tartaddress is routed to Beginthreadex, you must use the stdcall calling convention and you must return a thread exit code.
Beginthreadex returns 0 instead of 1 when it fails.
. Eginthreadex the thread that was established terminates by calling Endthreadex.
You can explicitly call Endthread or endthreadex to terminate a thread, but automatically invoke Endthread or Endthreadex when the thread returns from a routine passed as a parameter. Terminating a thread by calling Endthread or Endthreadex helps ensure that the resource allocated by the thread is restored.
Endthread automatically closes the line Cheng (and Endthreadex does not), so when Beginthread and Endthread are used, the thread handle is not explicitly closed by invoking the Win32 CloseHandle API function. This behavior differs from the Win32 ExitThread API function.
Note: Do not call the Win32exitthread API function for executables that are linked to LIBCMT.LIB, which prevents the running system from requiring that the allocated resources be retracted. Endthread and Endthreadex require that the allocated thread resources be retracted, and then call ExitThread. When Beginthread or Beginthreadex are invoked, the operating system handles the stack allocation you do not need to transfer the thread stack address to these functions. In addition, the StackSize parameter can be 0, in which case the operating system uses the same value as the stack specified in the main thread.
ArgList is the parameter that is passed to the newly established thread. It is usually the address of a data item such as a string.
arglist If you do not need to be nullable, Beginthread and Beginthreadex must provide some values that are passed to the new thread. If any thread calls Abort, exit, exit, or ExitProcess, the thread that is used is terminated.

When writing C + + code, keep in mind a word: should never call CreateThread. Instead, you should use the Visual C + + Run-time library function _beginthreadex.

As if the CreateThread function is a tiger, why does Microsoft want to develop this function?

From the relevant information found on the Internet, now a summary of the relevant staff to thank.

From "Windows core Programming":

The CreateThread function is the Windows function used to create a thread. However, if you are writing C + + code, you should never call CreateThread. Instead, you should use the Visual C + + Run-time library function _beginthreadex. If you do not use Microsoft's Visual C + + compiler, your compiler vendor has its own createthred substitution function.

To enable multithreaded C and C + + programs to run correctly, you must create a data structure and associate it with each thread that uses the C + + run-time library function. When you call the C + + Run-time Library, these functions must know to view the data blocks of the calling thread, so that they do not adversely affect other threads.

1. Each thread obtains its own tiddata memory structure that is allocated by the stack of the C + + Run-time library.

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 within, 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.

The difference between _beginthreadex and _beginthread functions. The _beginthread function has fewer parameters, so the _beginthreadex function is more restrictive than the comprehensive feature.

For example, if you use _beginthread, you cannot create a new thread with security attributes, you cannot create a paused thread, and you cannot obtain the thread's ID value.

The following excerpt from The Holly () post in CSDN is explained and thanked again.

Source: http://topic.csdn.net/t/20000926/10/31810.html

Holly ():

Oldworm provides examples of good use, and also uses compiler control.

Let me explain the theoretical difference:

CreateThread, _beginthread and _beginthreadex are all used to start the thread, but we see that Oldworm does not provide a way to _beginthread, the reason is simple, _beginthread is _ Beginthreadex a subset of functions, although _beginthread is called _beginthreadex but he masks features such as security features, so _beginthread and CreateThread are not the same level, _ Beginthreadex and CreateThread are completely replaceable in function, so let's compare _beginthreadex and createthread!

The CRT's function library existed before the thread appeared, so the original CRT could not really support the threads, which led us to choose the CRT library when we were programming, as we looked up the functions of the CRT in MSDN:


Libraries
LIBC. LIB single thread Static library, retail version
LIBCMT. LIB multithread Static Library, retail version
MSVCRT. LIB Import Library for MSVCRT. DLL, retail version

Such a hint.

Support for threads is a later matter.

This also led to many CRT functions in the case of multithreading must have special support, can not simply use the CreateThread on OK.

Most CRT functions can be used in CreateThread threads, and the data says that only the signal () function is not allowed to cause the process to terminate. But you can use it not to say that there is no problem.

Functions such as malloc (), fopen (), _open (), Strtok (), CTime (), or localtime () require specialized thread-locally-stored blocks of data, which typically need to be created when a thread is built, If you use CreateThread, this block of data is not established, and then what happens. In such a thread, you can still use these functions and there is no error, in fact the function found that the pointer to this block is empty, it will build one, and then associate it with the thread, which means that if you use CreateThread to create a thread, and then use such a function, There will be a piece of memory unknowingly created, unfortunately, these functions do not delete it, and CreateThread and ExitThread can not know this matter, so there will be memory leak, in the process of frequently launched software (such as some server software), Sooner or later, your system will run out of memory resources.

_beginthreadex (internal also call CreateThread) and _endthreadex on this block of memory processing, so there is no problem. (no one will intentionally use CreateThread to create and then terminate with _endthreadex, and thread termination is best not to explicitly call the termination function, natural exit best.) )

When it comes to the problem of handle, _beginthread's corresponding function _endthread automatically calls CloseHandle, and _beginthreadex's corresponding function is not _endthreadex. So CloseHandle is going to call it anyway, but _endthread can help you do it without writing, and you need to write the other two. (Jeffrey Richter strongly recommended that as far as possible without explicit termination function, with natural exit, natural exit of course must write their own closehandle)

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.