Windows via C ++: Windows Thread Synchronization

Source: Internet
Author: User

 

From: dream in the End of the World C ++ blog (http://www.cppblog.com/mzty)

One thread

1) if you are writing C/C ++CodeYou must never call createthread. Instead, use the library function _ beginthreadex during the runtime of VisualC ++, and use _ endthreadex to exit. If Microsoft's VisualC ++ compiler is not used, your compiler vendor has its own createthred alternative function. No matter what this alternative function is, you must use it.


2) Because _ beginthreadex and _ endthreadex are CRT thread functions, you must pay attention to the runtimelibaray compilation option and use Mt or MTD.

3)
The parameter list of the _ beginthreadex function is the same as that of the createthread function, but the parameter name and type are different. This is because Microsoft's C/C ++ Runtime Library Development Team believes that C/C ++ runtime functions should not have any dependency on Windows data types. The _ beginthreadex function also returns the handle of the newly created thread like createthread.

4) The following are some key points about _ beginthreadex:

• Each thread obtains its own tiddata memory structure allocated by the stack of the C/C ++ runtime database. (The tiddata structure is located in the VisualC ++ of mtdll. h file.Source code).

• The address of the thread function passed to _ beginthreadex is stored in the tiddata memory block. Parameters passed to the function are also saved in the data block.

• _ Beginthreadex does call createthread internally, because this is the only way the operating system knows how to create a new thread.

• When createtthread is called, it is notified to start the new thread by calling _ threadstartex instead of pfnstartaddr. Also, the parameter passed to the thread function is the tiddata structure rather than the pvparam address.

• If everything goes well, the thread handle will be returned like createthread. If any operation fails, null is returned.

5) _ endthreadex highlights:

• The _ getptd function of the C Runtime Library calls the tlsgetvalue function of the operating system internally, which is used to retrieve the address of the tiddata memory block of the calling thread.

• The data block is then released, and the exitthread function of the operating system is called to truly cancel the thread. Of course, exit code should be correctly set and passed.

6) Although the simplified version of _ beginthread and _ endthread are also provided, the controllability is too poor, so it is generally not used.

6) because the thread handle is a kernel object, close handle at the end.

7) the termination of the C ++ main thread also terminates all the subthreads created by the main thread. Whether the execution of the non-pipe thread has been completed or not.

8) If a thread is suspended and waitforsingleobject is called to wait for the thread, a deadlock will occur.

Two-thread synchronization-critical sections

1) Because critical sections is not a kernel object, it can only be used for synchronization between threads in the same process. It cannot be used for synchronization between multiple threads in different processes.

2) If
SuddenlyProgramCrash or exit without calling leavecriticalsection, the result is that the kernel corresponding to the thread cannot be released and the thread becomes a dead thread.

3) faster than other kernel objects.

4) good encapsulation:

Class critsect
{
Public:
Friend class lock;
Critsect (){
Initializecriticalsection (& _ critsection );}
~ Critsect (){
Deletecriticalsection (& _ critsection );}
PRIVATE:
Void
Acquire () {entercriticalsection (& _ critsection );}
Void
Release () {leavecriticalsection (& _ critsection );}

Critical_section _ critsection;
};

Class lock
{
Public:
Lock (critsect &
Critsect): _ critsect (critsect) {_ critsect. Acquire ();}

~ Lock () {_ critsect. Release ();}
PRIVATE:
Critsect &
_ Critsect;
};
Call: critsect sect; lock (SECT );

Mutex for three-Thread Synchronization


1) The mutex Kernel Object ensures that the thread has mutex access to a single resource. In fact, mutex objects are named accordingly. A mutex object contains a quantity, a thread ID, and a recursive counter.
2)
The behavior of the mutex object is the same as that of the key code segment, but the mutex object belongs to the kernel object, and the key code segment belongs to the user mode object. This means that mutex objects run slowly than key code segments. However, this also means that multiple threads in different processes can access a single mutex object, and this means that a timeout value can be set when the thread is waiting to access the resource.

3) ID is used to identify which thread in the system has a mutex object. Recursive counters are used to specify the number of times that the thread has a mutex object.

4)
Mutex objects have many purposes and are one of the most common kernel objects. Generally, they are used to protect memory blocks accessed by multiple threads. If multiple threads need to access the memory block at the same time, the data in the memory block may be damaged. The mutex object can ensure that any thread accessing the memory block has exclusive access to the memory block, thus ensuring data integrity.

5) the rules for using mutex objects are as follows:

• If the thread ID is 0 (this is an invalid ID), the mutex object is not owned by any thread and sends a notification to this mutex object.

• If the ID is a non-zero number, a thread has a mutex object and does not send a notification to the mutex object.

• Unlike all other kernel objects, mutex objects have special code in the operating system, allowing them to violate normal rules.


Event of Four-Thread Synchronization

1) among all kernel objects, the event kernel object is the most basic object. They contain a count (the same as all kernel objects), a Boolean value indicating whether the event is an automatically reset event or a manually reset event, another Boolean value used to indicate whether the event is in the notified or not notified status.

2) an event can notify you that an operation has been completed. There are two different types of event objects. One is a manual reset event, and the other is an automatic reset event. When a manually reset event is notified, all threads waiting for the event change to schedulable threads. When an automatically reset event is notified, only one thread in the thread waiting for the event changes to a schedulable thread.

3) when one thread executes the initialization operation and notifies another thread to execute the remaining operations, the event is used most. The event is initialized to the state of not notified. After the thread completes its initialization, it sets the event to the notified State. At this time, another thread waiting for the event finds that the event has been notified, so it becomes a schedulable thread.

4) Microsoft defines a side-effect rule that should be successfully waited for automatically reset events, that is, when the thread successfully waits for the object, events that are automatically reset to the state of no notification. This is how events that are automatically reset obtain their names. Generally, there is no need to call the resetevent function for automatically reset events, because the system will automatically reset the events. However, Microsoft does not define the side effects of a successful wait for a manually reset event, so you need to call resetevent ().

Other five-Thread Synchronization

1) local thread storage
(TLS). All threads in the same process share the same virtual address space. Local variables in different threads have different copies, but static and globl variables are shared by all threads in the same process. Using TLS technology, you can create an array for static and globl variables based on the number of threads of the current process. Each thread can access the corresponding variables through the index of the array, this ensures that the static and global variables create different copies for each thread.

2) The family of mutual lock functions is very large, such as interlockedexchangeadd ()..., the advantage of using the mutual lock function is that it is much faster than other criticalsection, mutex, event, and semaphore.

3) Wait function. For example, the waitforsingleobject function is used to detect the signal status of the hhandle event. When the function execution time exceeds dwmilliseconds
But if the dwmilliseconds parameter is infinite, the function will not return until the corresponding time event changes to a signal state. Otherwise, it will wait
Waitforsingleobject only executes the code after it returns the result.

6. Windows core programming (English Version 5th)
For more information about the best windows multi-threaded programming, see the original book.

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.