C + + multithreaded programming to create a new thread

Source: Internet
Author: User
Tags array length function prototype

Multi-threaded synchronization mutex, mutual exclusion refers to a resource for a period of time to allow only one visitor to access, synchronization is on the basis of mutual exclusion, multiple threads or processes in a certain order to run.


The C + + language itself does not provide a multithreaded mechanism, and the Windows system provides us with the relevant APIs.

WINDOWSAPI provides a function CreateThread (), the basic process of which is:

1. Assign a thread ID/handle to the kernel object to be managed and returned by CreateThread
2. The thread exit code is set to Still_active, the thread hangs count to 1
3. Assigning context structure
4. Allocate two pages of physical storage to prepare stack, protect page set to Page_readwrite, page 2nd set to Page_guard
5.lpStartAddr and Lpvthread values are placed on top of the stack, making them the parameters to be transmitted to Startofthread
6. Point the stack pointer of the context structure to the top of the stack (step 5th) instruction pointer pointing to Startofthread function


function is

Handlewinapicreatethread (

Lpsecurity_attributeslpthreadattributes,

Size_tdwstacksize,

Lpthread_start_routinelpstartaddress,

Lpvoidlpparameter,

Dworddwcreationflags,

Lpdwordlpthreadid

);
The first parameter is the thread kernel security attribute, and the default is null.

The second parameter is the space size of the line stacks, passing in 0 means using the default size of 1MB, and Windows dynamically extends the stack size according to the situation.

The third parameter is the thread function address, using Dwordwinapithreadproc (Lpvoidpparam), to declare a thread function. (DWORD is double word is 32bit,4 byte, lpvoid is void pointer, point to function parameter)

The fourth parameter is the argument passed to the thread function.

The fifth function specifies the additional flags to control the creation of the thread, which is dispatched immediately after the thread is created, and create_suspended to indicate that the thread was created and paused until the ResumeThread (HANDLE) was invoked.

The sixth parameter returns the thread ID number and, if NULL, does not return, and assigns the ID to the address that the pointer points to.

Several commonly used functions in multiple threads:

GetCurrentThreadID () returns the thread ID.

WaitForSingleObject

function function: Wait function-Causes the thread to enter the wait state until the specified kernel object is triggered.

Function prototype:

Dwordwinapiwaitforsingleobject (

Handlehhandle,

Dworddwmilliseconds

);

Function Description:

The first parameter is the kernel object to wait on.

The second parameter is the longest waiting time, in milliseconds, such as incoming 5000 for 5 seconds, incoming 0 returns immediately, and the incoming infinite represents an infinite wait.

Because the thread's handle is not triggered while the thread is running, the handle is in the firing state when it finishes running. So you can use WaitForSingleObject () to wait for a thread to finish running.

function return value:

The object is triggered within a specified time, and the function returns to WAIT_OBJECT_0. The maximum wait time object has not yet been triggered to return to Wait_timeout. An error in the incoming parameter will return wait_failed.

Waits for all thread handle execution end in array iphandles.

Dwordwaitformultipleobjects (
dwordncount,//Array length
consthandle*lphandles,//array pointer
boolbwaitall,//whether to wait for all threads
dworddwmilliseconds//Maximum wait time
);



The reason for not recommending using CreateThread is that for multiple threads to be considered in the C language, such as using global variable errno, the thread is unsafe for functions such as strerror (), Strtok (), Tmpnam (), Gmtime (), So the compiler recommends a new version of the thread-safe use of these functions, or a thread-safe function _beginthreadex ().


_beginthreadex ():

The thread-safe solution to the standard C library is to configure a proprietary memory area for use by functions in the C library for any thread.

It turns out that it's not necessary to use this function for the current compiler, because the thread-safe new function of the previous functions gives a compile error, and the advantage of the thread-safety of the function is gone, and for a function that is already thread-safe, This function creates a new memory area to hold the information is obviously a waste of space and time choices.

This function has the same approximate parameter as CreateThread, except that the return value type is uintptr_t, then the new thread is returned and the thread handle needs to be cast to the handle type.

The type of the thread function is Unsigned__stdcallfun (void*);

1th parameter: Security property, NULL is the default security property//2nd parameter: Specifies the size of the thread stack. If 0, the thread stack size is the same as the thread that created it. General with 0//3rd parameters: Specifies the address of the thread function, that is, the function address that the thread invokes execution (with the function name, the function name is the address)//4th parameter: A pointer to the parameter of the thread, which can be converted into a pointer to the corresponding class by passing in the pointer to the object// 5th parameter: Thread initial state, 0: Run now; create_suspend:suspended (hanging)//6th parameter: Address Uintptr_t_beginthreadex for recording thread ID (//nativecode void* Security, Unsignedstack_size, unsigned (__stdcall*start_address) (void*), Void*arglist, Unsignedinitflag, unsigned* THRDADDR);


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.