Thread, critical section of the study

Source: Internet
Author: User
Tags terminates

A thread is an execution path to a process that contains independent stacks and CPU register states, each of which shares all of the process resources, including open files, signal identities, and dynamically allocated memory. All threads within a process use the same address space, and the execution of those threads is controlled by the system scheduler, which determines which thread is executable and when it executes the thread. Threads have priority, and lower priority threads must wait until the higher priority thread finishes executing. On multiprocessor machines, the scheduler can put multiple threads on different processors to run, which can balance the processor tasks and improve the efficiency of the system. The principle of multithreaded programming is consistent with the support of the MFC class Library in WIN32 mode, and the main thread of the process can create new threads whenever needed. Automatically terminates the thread when the thread finishes executing; When the process is finished, all threads are terminated. All active threads share the resources of the process, so when programming you need to consider the issue of conflicts when multiple threads access the same resource. When a thread is accessing a process object, and another thread is changing the object, it can produce incorrect results and resolve the conflict when programming. 1. Creating and terminating threads with the Win32 functionThe WIN32 function library provides functions to manipulate multithreading, including creating threads, terminating threads, establishing mutex zones, and so on. The functions for creating new threads in the main thread of the application or in other active threads are as follows: HANDLE CreateThread (lpsecurity_attributes lpthreadattributes,dword dwstacksize, Lpthread_start_routine lpstartaddress,lpvoid Lpparameter,dword Dwcreationflags,lpdword lpThreadId);
Returns a handle to the thread if creation succeeds, otherwise null is returned. When a new thread is created, the thread starts executing. But if the create_suspended feature is used in dwCreationFlags, then the thread does not execute immediately, but hangs first, waits until the resumethread is called before starting the thread, and in this process can call the following function to set the priority of the thread: BOOL setthreadpriority (HANDLE hthread,int npriority); When the calling thread's function returns, the thread terminates automatically. If you need to terminating during thread executionThe function can be called: VOID exitthread (DWORD dwexitcode); thread out of thread termination, you can call the following function: BOOL terminatethread (HANDLE hthread,dword dwexitcode), but note that this function may cause system instability and the resources that the thread consumes are not freed. Therefore, it is generally not recommended to use this function. If the thread to be terminated is the last thread in the process, the corresponding process should also terminate after the thread is terminated. 2. Synchronization of ThreadsIn the thread body, if it is completely independent and conflicts with other threads that do not have resource operations such as data access, it can be programmed in a normally single-threaded way. However, this is often not the case with multithreading, where the threads often have to access some resources at the same time. Since access to shared resources is unavoidable, in order to resolve this thread synchronization problem, the Win32 API provides a variety of synchronization control objects to help programmers resolve shared resource access violations. Before introducing these synchronization objects, let's introduce the wait function, because the function is used for all control object access control. The Win32 API provides a set of wait functions that enable a thread to block its own execution. These functions are returned after one or more of the synchronization objects in their parameters have signaled, or after the specified wait time has passed. When the wait function is not returned, the thread is in a wait state, at which point threads consume only a small amount of CPU time。 Using the wait function can not only guarantee the synchronization of threads, but also improve the running efficiency of the program. The most common wait functions are: DWORD WaitForSingleObject (HANDLE hhandle,dword dwmilliseconds); This function returns when the specified object was in the signaled state or when the time-out interval elapses. and the function Waitform Ultipleobject can be used to simultaneously monitor multiple synchronization objects, the declaration of which is: DWORD Waitformultipleobject (DWORD ncount,const HANDLE *lphandles,bool bWaitAll, DWORD dwmilliseconds); Here are some of the objects that handle the critical section (1) Mutex object MutexThe state of a mutex object is signaled when it is not owned by any thread, and no signal when it is owned. A mutex object is ideal for reconciling multiple threads with mutually exclusive access to shared resources. You can use this object as follows: First, create a mutex object, get the handle: HANDLE CreateMutex (); Then, before the thread can produce a conflicting zone (that is, before accessing the shared resource), call WaitForSingleObject, pass the handle to the function, and request the mutex object: Dwwaitresult = WaitForSingleObject (Hmutex, 5000L); Access to the shared resource ends, freeing the mutex object: ReleaseMutex (Hmutex), the mutex object can only be occupied by one thread at the same time, and when the mutex object is occupied by one thread, if there is a second way to occupy it, You must wait until the previous thread has been released to succeed. (2) Signal ObjectThe signal object allows access to multiple threads sharing resources at the same time, specifying the maximum number of threads that can be accessed concurrently when the object is created. When a thread requests a successful access, the counter in the signal object is reduced by one, and after the ReleaseSemaphore function is called, the counter in the signal object is incremented by one. Where the counter value is greater than or equal to 0, but less than or equal to the maximum value specified at the time of creation. If an application creates a signal object, the initial value of its counter is set to 0, blocking other threads and protecting the resource. When initialization is complete, call the ReleaseSemaphore function to increase its counter to the maximum value for normal access. You can use this object as follows: First, create a signal object: HANDLE createsemaphore (); or open a Signal object: HANDLE OpenSemaphore (), and then call WaitForSingleObject before the thread accesses the shared resource. When access to a shared resource is complete, the occupancy of the signal object should be released: ReleaseSemaphore (); (3) Event objectThe event object is the simplest synchronization object, which consists of both signaled and no-signal states. Before a thread accesses a resource, it needs to wait for an event to occur, which is most appropriate for the event object. For example, the monitoring thread is activated only after the data is received by the communication port buffer.

The event object is built with the CreateEvent function. The function can specify the class of the event object and the initial state of the event. If the event is manually reset, it will always remain signaled until the ResetEvent function is reset to a signal-free event. If the event is automatically reset, its state will automatically become non-signaled when a single waiting thread is released. The event object can be set to a signal state using SetEvent. When an event is established, you can name the object so that threads in other processes can open the event object handle of the specified name with the OpenEvent function. (4) When the exclusion zone object is executed asynchronously in the exclusion zone, it can only share resource processing between threads in the same process. Although several of the methods described above can be used at this point, the use of exclusion zones makes synchronization management more efficient. When used, a critical_section object is defined, and the following function is called before the process is used to initialize the object: VOID initializecriticalsection (lpcritical_section); When a thread uses the exclusion zone, the function is called: EnterCriticalSection or tryentercriticalsection; Call the function leavecriticalsection when it is required to occupy and exit the exclusion zone, freeing the object from the exclusion zone for use by other threads.

Transferred from: http://blog.sina.com.cn/s/blog_7057cef40100q3oi.html

Thread, critical section of the study

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.