C + + Multithreading

Source: Internet
Author: User
Tags mutex semaphore terminates

1 Why multithreading is used

Time-consuming operations use threads to improve application responsiveness (especially important for graphical interface programs, multithreading ensures that the interface is not stuck and can still respond to the mouse)

Parallel operations use threads, such as servers, to respond to client requests.

Multi-CPU or multi-core system, multithreading increases CPU utilization (OS guarantees that the number of threads is not greater than the number of CPUs, different threads on different CPUs)

Improve the program structure.

2 Advantages of threading

Compared with the process, it is a small cost, switching fast, more frugal multi-tasking operation. Starting a new process must allocate a separate address space, create a large number of data tables to maintain its code snippets, stack segments and data segments, is an expensive multi-tasking approach, and if you use multiple threads in a process, sharing data with each other using the same address space, the cost of thread switching is minimal.

The other is the communication mechanism between threads. Different processes have independent data space, it is time-consuming and inconvenient to transmit data only by means of communication. Because the data space is shared between threads in the same process, the data for one thread can be used directly by other threads. Of course, the sharing of data between threads also brings some problems, so synchronization is required.

3 Understanding Threads

Processes: Each process consists of a private virtual address space, code, data, and other system resources. The resource that the process creates at run time dies as the process terminates .

Because the process has a separate address space, after a process crashes, in protected mode, no impact on other processes, multi-process programs than multithreaded robust.

Thread: A separate execution flow. The default run consists of a main line constant, the main thread in the form of a function address, such as the main () or WinMain function, the start point of the provider, and when the main thread terminates, the process also terminates.

All threads in a process are in the virtual space of the process, using the process's global variables and system resources. CPU time slice rotation of the way scheduling, high priority first run.

4 Thread Classification

  User interface threads: typically used to process user input and respond to various events and messages, in fact, the application's main execution thread CWinApp object is a user interface thread, when the application starts automatically created and started, as well as its termination also means that the program ends, the process terminates.

Worker thread (Background thread): The background processing task of executing the program, such as computation, scheduling, reading and writing to the serial port, and the user interface, is not to be created from the CWinThread class derivation. worker threads and user interface threads are called to invoke different versions of the same function when they are started.

5 Threads

5.1 thread Composition: thread consists of thread ID, current instruction pointer (PC), register collection, and stack.

  5.2 Thread Status: Ready (Waiting for processor), blocking (waiting for event), running.

6 thread synchronization Mutex 4 ways

  6.1 Critical Zone (cirtical section): For use when multiple threads in a process access a common area or code snippet.

InitializeCriticalSection, DeleteCriticalSection, EnterCriticalSection, leavecriticalsection

Note: entercriticalsection, a thread can enter critical areas multiple times

Find the definition of key section critical_section first, it is defined as rtl_critical_section in WinBase.h. and rtl_critical_section in WinNT.h that it is actually a struct:

Typedefstruct _rtl_critical_section {

Prtl_critical_section_debug Debuginfo; Debugging-related

LONG Lockcount; n indicates that there are N threads waiting

Longrecursioncount; The number of critical segments that a thread with this critical segment has received for this resource

Handleowningthread; The thread handle that holds the key segment, from the thread's Clientid->uniquethread

HANDLE LockSemaphore; A self-resetting event

DWORD Spincount; Rotation lock settings, single CPU under ignore

} rtl_critical_section, *prtl_critical_section;

It is up to this structure to know that the critical segment will record the thread handle that holds the critical segment and that the critical segment has a "thread ownership" concept . The fourth parameter, OwningThread, records the thread handle that is allowed to enter the critical area, and if the thread enters again, enterciritcalsection () updates the third parameter recursioncount, To record the number of times the thread has entered and return it immediately to get the thread into it. Once the thread ownership thread calls LeaveCriticalSection () to enter the number of 0 o'clock, the system automatically updates the critical segment and returns the waiting thread back to the scheduled state.

Note: Threads that have thread ownership can repeatedly enter the critical code area.

In addition, because of the overhead of switching threads to wait states, to improve the performance of critical segments, Microsoft merges rotation locks into critical segments so that entercriticalsection () loops with a rotation lock first. Attempts to switch threads to a wait state for a period of time. the eighth chapter of the fifth edition of Windows core programming recommends the use of rotary locks while using critical segments, which helps improve performance. It is important to note that setting a rotation lock is not valid if the host has only one processor . Threads that fail to enter critical areas are always switched to the wait state by the system.

Here is the key segment initialization function with the rotation lock

function function: Initialize key segment and set number of rotations

Function Prototypes:

Boolinitializecriticalsectionandspincount (

Lpcritical_sectionlpcriticalsection,

Dworddwspincount);

Function Description: The number of rotations is generally set to 4000.

function function: Change the number of rotations of a key segment

Function Prototypes:

Dwordsetcriticalsectionspincount (

Lpcritical_sectionlpcriticalsection,

Dworddwspincount);

6.2 Mutex (Mutex): used in different in-process multithreaded access to common areas or code snippets, similar to the critical section.

CreateMutex, CloseHandle, WaitForSingleObject, ReleaseMutex.

A mutex is also a kernel object that is used to ensure that a thread is exclusive of access to a resource. Mutexes are very similar to the behavior of critical segments, and mutexes can be used for mutually exclusive access to resources in different processes. Using mutex mutexes will primarily use four functions.

Handlecreatemutex (

Lpsecurity_attributeslpmutexattributes,//Indicates security control, general direct pass-through null

Boolbinitialowner, //whether the creator (the main thread in this case) owns the mutex, and the same as the critical section, there is a problem of ownership

If ture, indicates that the current creation thread owns the mutex;

If False, the first thread that calls Waitforsngleobject will have the mutex.

Lpctstrlpname,

);

Note: The mutex also has thread-path ownership issues, and the threads that own this mutex call Waitforsngleobject and will get this mutex without blocking.

6.3 Event: A synchronous mutex is implemented by triggering an event between threads.

CreateEvent, CloseHandle, SetEvent, resetevent

HANDLE CreateEvent (

Lpsecurity_attributes lpeventattributes,//indicates security control, and generally passes directly to NULL.

Boolb manualreset,//manual or automatic reset.

BOOL Binitialstate,//whether the initial state is already triggered.

LPCTSTR the name of the Lpname//event, and Null indicates an anonymous event.

);

6.4 Semaphore (Semaphore): Unlike critical zones and mutexes, multiple threads can simultaneously access common area data, similar to the PV operation in the OS, setting a maximum number of threads to access a common area, minus one per thread access to the share, until the resource is small and equal to 0.

CreateSemaphore, CloseHandle, WaitForSingleObject, ReleaseSemaphore

Note: Semaphore does not have the concept of ownership, a thread can repeatedly call wait ... () function to generate a new lock. This is not the same as a mutex: the thread that owns the mutex no matter how many times it is called wait ... () function, and it will not be blocked.

6 Thread resolution

Windows provides two types of threads, worker threads, and user interface threads. Both of these threads are supported by the MFC library. The user interface thread usually has a window, so it has its own message loop. The worker thread does not have a window, so it does not need to process the message. Worker threads are easier to program and often more useful

Each thread has its own proprietary register (stack pointer, program counter), but the code area is shared.

Program Counter: The program counter is the place to hold the address of the unit where the next instruction is located.

C + + Multithreading

Related Article

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.