VC + + Learning Multi-Threading (2)

Source: Internet
Author: User

Create a thread that naturally has a corresponding system API to complete. CreateThread This function is used to create threads.

The use of various parameters I will not say more, here directly to the example of my own practice



1, the following is an example of creating a thread, of course, is simply created;

#include <windows.h> #include <iostream>using namespace Std;dword WINAPI Fun1pro (LPVOID laparameter); int Main () {HANDLE hthread1;hthread1 = CreateThread (null, 0, Fun1pro, NULL, 0, NULL); CloseHandle (HTHREAD1); cout << "main thread is running \ n"; return 0;} DWORD WINAPI Fun1pro (lpvoid laparameter) {printf ("The New Thread is running\n"); return 0;}
In C + +, the reference to an object is also handled by reference counting, so the CloseHandle function in the code above simply closes a handle to the thread in the main threads, but the new thread actually created still exists. Only the reference count for this thread in the kernel object of this new thread is 1. Otherwise, if you do not execute such a function, even if the thread is executed, the thread's reference count is not 0 because it still has traces in the main thread, and it cannot be completely deleted until the entire process counts.


After running this program can be found, and do not see the new thread output that sentence.

The reason is that the process started after the main thread, because the operating system is assigned to the thread time slice of the way to let the thread run, so, in the main thread of the time slice, no special situation is no one interrupted him, has been executing, to create a new sub-thread, because the main thread of the time slice does not arrive, so, Not be able to execute the child thread, and then immediately close the handle of the child thread, the main thread is finished, it means that the whole process is over, all the resources are recycled, the child threads are basically useless. If you want to see a child thread running, then you need to have the main thread suspend execution, and the dispatcher in the operating system will find a new thread in the queue to execute.

The way to stop a thread from running is to use the sleep () function to make it pause.

You can return 0 in the main function, and with sleep in front of the statement, it pauses before the main thread ends to execute the new child thread.


So what exactly is the main thread and the sub-thread running in their direct order? Since the running time of the threads and processes is determined by the time slices of the operating system, I have made the following modifications to the code:

#include <windows.h> #include <iostream>using namespace Std;dword WINAPI Fun1pro (LPVOID laparameter); int index = 0;int Main () {index = 0; HANDLE hthread1;hthread1 = CreateThread (null, 0, Fun1pro, NULL, 0, NULL); CloseHandle (HTHREAD1); while (index++<100) cout << "main thread is running \ n";//sleep (+); return 0;} DWORD WINAPI Fun1pro (LPVOID laparameter) {while (index++<100) printf ("The New Thread is running\n"); return 0;}

Run results




We can confirm the above mentioned, the running time of the thread is determined by the time slice, when the main thread time slice runs out, but the entire main thread has not finished running, the operating system dispatcher will also join the thread's ready queue, from the queue to find a new sub-process to execute.



2, using mutually exclusive objects to achieve synchronization:

A mutex is a kernel object that guarantees that a thread has exclusive access to a single resource, that is, only one thread can access the resource at the same time. A mutex object includes: Use number, thread ID, counter. The ID indicates which thread now owns the mutex, and the counter is used to indicate the number of times that the thread owns the mutex object.

You need to call the CreateMutex function to create the mutex object. The mutex object is requested through the WaitForSingleObject function, and the mutex object is freed through the ReleaseMutex function.

It is possible to see here that there is still no reason why mutexes can achieve synchronization between processes.

First, we want to create a mutex object, at this time the mutex is in a signaled state, when we use the wait function to request a mutex, then we now this thread is able to obtain access to the mutex object, and thus began to execute the wait function after the shared code area, while the When a wait is called, the mutex is changed from a signal to a non-signaled state, because the mutex is guaranteed mutually exclusive access to a single resource, and if there are other new threads that request access to the mutex to execute the shared code, then the mutex object he gets at this time is no signal state, is not able to proceed, the thread is in a wait state. When the first thread finishes executing the shared code area, we want to release the mutex that we are using now, that is, to release it with ReleaseMutex, and he sets the mutex from the signal-free State to the signaled state, at which point, according to the order of the request, One of the two threads that previously waited for a mutex signal in the wait function would be allowed access to the mutually exclusive object to execute the code for the shared store.


In fact, the above mutex and the operating system of the PV operation is the same.

The shared code is the code between the wait function and the release function, allowing only one thread to gain access to the mutex at a time to enter the critical section. Wait is the request operation, and release is the recovery operation.


There is also an important mechanism for mutex objects, Is the ID of the thread that he includes. If thread 1 requests a mutex, then if the line Cheng wants to use this mutex, it must be released by thread 1, and in the process of releasing, the mutex will take out the thread ID that he maintains and compare it with the thread that freed it, otherwise the mutex object can be released if the thread I D is not the same as the release, it is not possible to release the mutex object.


The second parameter in the CreateMutex function has two values, and the other is false, One is true.false represents the current thread does not own this mutex object, the mutex is signaled state, true indicates that the current thread owns this mutex, that is, the current thread and the mutex binding, the mutex object is in a signal-free State, equivalent to the default execution of the wait function. If the wait function is called in this thread at this point, although the mutex is not signaled, it will still get control of the mutex because the thread ID that is maintained inside the thread and the mutex is equal. But at this point, there is a very important point is that the mutex object counter + 1. From the outset, the counter of the mutex represents the number of times the thread owning the mutex has it, so the counter will be +1 whenever the wait function is called. Therefore, if the current thread does not need this mutex, it needs to call two release function, the counter will be reduced to 0, This also tells us that the function of releasing the function is actually to let the counter-1.


3. There is also a very important function about the mutex object:

When a thread uses the wait function to request a mutex, the release function is not called to release the object, so the operating system will automatically release the mutex and turn it into a signaled state after the thread has terminated.




4. How to ensure that only one instance runs:

We all know that the program is just code, a program can have more than one instance, then if only one instance of the program is running. The solution is to use the named mutex object to implement it. The reason is that if you call a function that creates a mutex, if the previously named mutex exists, it returns the mutex that was created and no longer creates a new one, and GetLastError returns error_alreday_exists.

So, if CreateMutex returns a valid handle, then it is necessary to determine what the return value of GetLastError is, and thus determine whether we have previously created a mutex object, which is equivalent to having an instance running.


VC + + Learning Multi-Threading (2)

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.