_ Beginthread () and _ beginthreadex ()

Source: Internet
Author: User

Create a thread.

Uintptr_t _ beginthread (
Void (_ cdecl *Start_address) (Void *),
UnsignedStack_size,
Void *Arglist
);
Uintptr_t _ beginthreadex (
Void *Security,
UnsignedStack_size,
Unsigned (_ stdcall *Start_address) (Void *),
Void *Arglist,
UnsignedInitflag,
Unsigned *Thrdaddr
); Parameters
Start_address
Start address of routine that begins execution of new thread.
Stack_size
Stack size for new thread or 0.
Arglist
Argument list to be passed to new thread or null.
Security
Pointer to a security_attributes structure that determines whether the returned handle can be inherited by child processes. If null, the handle cannot be inherited. Must be null for Windows 95 applications.
Initflag
Initial State of New thread (0 for running or create_susponded for susponded); Use resumethread to execute the thread.
Thrdaddr
Points to a 32-bit variable that has es the thread identifier.

Return Value
If successful, each of these functions returns a handle to the newly created thread. _ beginthread returns-1l on an error, in which case errno is set to eagain if there are too threads, or to einval if the argument is invalid or the stack size is incorrect. _ beginthreadex returns 0 on an error, in which case errno and _ doserrno are set.
Remarks
The_ BeginthreadFunction creates a thread that begins execution of a routine Start_address. The routine Start_addressMust use_ CdeclCalling convention and shocould have no return value. When the thread returns from that routine, it is terminated automatically.
_ BeginthreadexResembles the Win32 createthread API more closely than _ beginthread does._ BeginthreadexDiffers from_ BeginthreadIn the following ways:
1. _ beginthreadexHas three additional parameters:Initflag, security, threadaddr. The new thread can be created in a susponded state, with a specified security (Windows NT only), and can be accessed usingThrdaddr, Which is the thread identifier.
The routineStart_addressPassed_ BeginthreadexMust use the _ stdcall calling convention and must return a thread exit code.
_ BeginthreadexReturns 0 on failure, rather than-1l.
A thread created_ BeginthreadexIs terminated by a call_ Endthreadex.
2. _ beginthreadexFunction gives you more control over how the thread is created_ BeginthreadDoes._ EndthreadexFunction is also more flexible. For example,_ Beginthreadex, You can use security information, set the initial state of the thread (running or susponded), and get the thread identifier of the newly created thread. you are also able to use the thread handle returned_ BeginthreadexWith the synchronization APIs, which you cannot do_ Beginthread.
3.It is safer to use_ BeginthreadexThan_ Beginthread. If the thread spawned_ BeginthreadExits quickly, the handle returned to the caller_ BeginthreadMay be invalid or, worse, point to another thread. However, the handle returned_ BeginthreadexHas to be closed by the caller_ Beginthreadex, So it is guaranteed to be a valid handle if_ BeginthreadexDid not return an error.
You can call_ EndthreadOr_ EndthreadexExplicitly to terminate a thread; however,_ EndthreadOr_ EndthreadexIs called automatically when the thread returns from the routine passed as a parameter. terminating a thread with a callEndthreadOr_ Endthreadex Helps to ensure proper recovery of resources allocated for the thread.
_ Endthread
Automatically closes the thread handle (whereas_ EndthreadexDoes not). Therefore, when using_ BeginthreadAnd_ Endthread,Do not explicitly close the thread handle by calling the Win32 closehandle API. This behavior differs from the Win32 exitthread API.
NoteFor an executable file linked with libcmt. Lib, do not call the Win32ExitthreadAPI; this prevents the run-time system from reclaiming allocated resources._ EndthreadAnd_ EndthreadexReclaim allocated thread resources and then call exitthread.
The operating system handles the allocation of the stack when either_ BeginthreadOr_ BeginthreadexIs called; you do not need to pass the address of the thread stack to either of these functions. In addition,Stack_sizeArgument can be 0,In which case the operating system uses the same value as the stack specified for the main thread.
ArglistIs a parameter to be passed to the newly created thread. Typically it is the address of a data item, such as a character string.ArglistMay be null if it is not needed,_ BeginthreadAnd_ BeginthreadexMust be provided with some value to pass to the new thread. All threads are terminated if any thread callabort, exit, _ exit, or exitprocess.


Libraries
Multithreaded versions of the C run-time libraries only.
To use _ beginthread or _ beginthreadex, the application must link with one of the multithreaded C run-time libraries.
Example
The following example uses_ BeginthreadAnd_ Endthread.
// Crt_begthrd.c
// Compile with:/MT/D "_ x86 _"/C
# Include <windows. h>
# Include <process. h>/* _ beginthread, _ endthread */
# Include <stddef. h>
# Include <stdlib. h>
# Include <conio. h>

Void bounce (void * Ch );
Void checkkey (void * dummy );

/* Getrandom returns a random integer between min and max .*/
# Define getrandom (Min, max) (RAND () % (INT) (max) + 1)-(min) + (min ))

Bool repeat = true;/* Global repeat flag and Video Variable */
Handle hstdout;/* handle for Console window */
Console_screen_buffer_info CSBi;/* console information structure */

Int main ()
{
Char CH = 'a ';

Hstdout = getstdhandle (std_output_handle );

/* Get display screen's text row and column information .*/
Getconsolescreenbufferinfo (hstdout, & CSBi );

/* Launch checkkey thread to check for terminating keystroke .*/
_ Beginthread (checkkey, 0, null );

/* Loop until checkkey terminates program .*/
While (Repeat)
{
/* On first loops, launch character threads .*/
_ Beginthread (bounce, 0, (void *) (CH ++ ));

/* Wait one second between loops .*/
Sleep (1000l );
}
}

/* Checkkey-thread to wait for a keystroke, then clear repeat flag .*/
Void checkkey (void * dummy)
{
_ Getch ();
Repeat = 0;/* _ endthread implied */

}

/* Bounce-thread to create and control a colored letter that moves
* Around on the screen.
*
* Params: ch-the letter to be moved
*/
Void bounce (void * Ch)
{
/* Generate letter and color attribute from thread argument .*/
Char blankcell = 0x20;
Char blockcell = (char) ch;
Bool first = true;
Coord oldcoord, newcoord;
DWORD result;

/* Seed random number generator and get initial location .*/
Srand (_ threadid );
Newcoord. x = getrandom (0, CSBi. dwsize. X-1 );
Newcoord. Y = getrandom (0, CSBi. dwsize. Y-1 );
While (Repeat)
{
/* Pause between loops .*/
Sleep (100l );

/* Blank out our old position on the screen, and draw new letter .*/
If (first)
First = false;
Else
Writeconsoleoutputcharacter (hstdout, & blankcell, 1, oldcoord, & result );
Writeconsoleoutputcharacter (hstdout, & blockcell, 1, newcoord, & result );

/* Increment the coordinate for next placement of the block .*/
Oldcoord. x = newcoord. X;
Oldcoord. Y = newcoord. Y;
Newcoord. x + = getrandom (-1, 1 );
Newcoord. Y + = getrandom (-1, 1 );

/* Correct placement (and beep) If about to go off the screen .*/
If (newcoord. x <0)
Newcoord. x = 1;
Else if (newcoord. x = CSBi. dwsize. X)
Newcoord. x = CSBi. dwsize. X-2;
Else if (newcoord. Y <0)
Newcoord. y = 1;
Else if (newcoord. Y = CSBi. dwsize. Y)
Newcoord. Y = CSBi. dwsize. Y-2;

/* If not at a screen border, continue, otherwise beep .*/
Else
Continue;
Beep (char) ch-'A') * 100,175 );
}
/* _ Endthread given to terminate */
_ Endthread ();
}
Input
Press any key to end
The following sample code demonstrates how you can use the thread handle returned by _ beginthreadex with the synchronization API waitforsingleobject. the main thread waits for the second thread to terminate before it continues. when the second thread CILS _ endthreadex, it causes its thread object to go To the signaled state. this allows the primary thread to continue running. this cannot be done with _ beginthread and _ endthread, because _ endthread callclosehandle, destroying the thread object before it can be set to the signaled state.
// Crt_begthrdex.cpp
// Compile with:/mt
# Include <windows. h>
# Include <stdio. h>
# Include <process. h>

Unsigned counter;
Unsigned _ stdcall secondthreadfunc (void * parguments)
{
Printf ("in second thread.../N ");

While (counter< 1000000)
Counter ++;

_ Endthreadex (0 );
Return 0;
}

Int main ()
{
Handle hthread;
Unsigned threadid;

Printf ("creating second thread.../N ");

// Create the second thread.
Hthread = (handle) _ beginthreadex (null, 0, & secondthreadfunc, null, 0, & threadid );

// Wait until second thread terminates. If you comment out of the line
// Below, counter will not be correct because the thread has not
// Terminated, and counter most likely has not been incremented
/// 1000000 yet.
Waitforsingleobject (hthread, infinite );
Printf ("counter shocould be 1000000; it is-> % d/N", counter );
// Destroy the thread object.
Closehandle (hthread );
}
Output
Creating second thread...
In second thread...
Counter shoshould be 1000000; it is-> 1000000
 

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.