Createthread multi-thread programming test

Source: Internet
Author: User
In C ++, C ++ does not provide any multithreading mechanism, but in windows, we can call the SDK Win32 API to compile a multi-threaded program to create a thread function: handle createthread (
Lpsecurity_attributes lpthreadattributes, // SD
Size_t dwstacksize, // initial stack size
Lpthread_start_routine lpstartaddress, // thread function
Lpvoid lpparameter, // thread argument
DWORD dwcreationflags, // creation Option
Lpdword lpthreadid // thread identifier
);
Here we only use the third and fourth parameters, and the third parameter passes the address of a function, which is also the new thread we want to specify. The fourth parameter is the parameter pointer passed to the new thread.
Eg1: # include <iostream>
# Include <windows. h>
Using namespace STD; DWORD winapi fun (lpvoid lpparamter)
{
While (1) {cout <"Fun display! "<Endl ;}
} Int main ()
{
Handle hthread = createthread (null, 0, fun, null, 0, null );
Closehandle (hthread );
While (1) {cout <"main display! "<Endl ;}
Return 0;
} We can see that the main thread (main function) and our own thread (fun function) are randomly executed, but the output of the two threads is too fast, which makes it hard to see clearly, we can use functions
Void sleep (
DWORD dwmilliseconds // sleep time
);
To pause thread execution, dwmilliseconds indicates 1‰ seconds, so
Sleep (1000 );
Indicates to suspend eg2 for 1 second:

# Include <iostream>
# Include <windows. h>
Using namespace STD; DWORD winapi fun (lpvoid lpparamter)
{

While (1) {cout <"Fun display! "<Endl; sleep (1000 );}
} Int main ()
{
Handle hthread = createthread (null, 0, fun, null, 0, null );
Closehandle (hthread );
While (1) {cout <"main display! "<Endl; sleep (2000 );}
Return 0;
}
Execute the above Code. This time, we can clearly see that fun display is output on the screen! And main display !, We found that these two functions are indeed run concurrently. careful readers may find that our program outputs a line feed every time the fun function and main function output content, but we can see that sometimes the program outputs a line break, sometimes it does not output a line break, or sometimes it outputs two lines. What's going on? Next we will change the program to see:
Eg3:

# Include <iostream>
# Include <windows. h>
Using namespace STD; DWORD winapi fun (lpvoid lpparamter)
{

While (1) {cout <"Fun display! \ N "; sleep (1000 );}
} Int main ()
{
Handle hthread = createthread (null, 0, fun, null, 0, null );
Closehandle (hthread );
While (1) {cout <"main display! \ N "; sleep (2000 );}
Return 0;
}
When we run this program again, we find that, as we expected at this time, the content we want to output is correctly output and the format is correct. Next I will explain why our program was not correctly run. Multi-threaded programs run concurrently. If resources are shared among multiple threads, we cannot guarantee that these resources can be used correctly, because resources are not exclusive at this time, for example:
Eg4:
Add a resource int A = 3
There is a thread function selfadd () which is used to make a = a +
Another thread function, selfsub (), is used to make a = a-

Let's assume that the above two threads are waiting for a concurrent job. If selfadd is executing, we want to program a 6, but at this time selfsub gets the chance to run, so a becomes 0, and after selfadd reaches the execution opportunity, a = a + A, but at this time a is 0, not 6 as we expected, let's go back to eg2. Here, we can regard the screen as a resource which is shared by two threads. When the fun function outputs fun display! The Endl will be output (that is, clearing the buffer and wrapping the line, here we do not need to understand what the buffer is), but at this time the main function is indeed a chance to run, at this time, the fun function has not had time to output line breaks, so the CPU is given to the main function, and the main function is directly in the fun
Display! And output main display !, As to why sometimes the program outputs two line breaks in a row, the reader can use the same analysis method for analysis. Here I will not talk much about it and leave it to the reader to think for himself.
So why can we run eg2 correctly with eg3? The reason is that multiple threads run concurrently, but some operations must be in one breath and cannot be interrupted. Therefore, we can see that the running results of eg2 and eg3 are different. So, isn't the eg2 code that we can't let it run correctly? The answer is, of course, whether or not. Next I will explain how to make the eg2 code run correctly. This involves multi-thread synchronization. If a resource is shared by multiple threads, program confusion will occur. Our solution is to allow only one thread to exclusively share the resources. This will solve the above problem.
Handle createmutex (
Lpsecurity_attributes lpmutexattributes, // SD
Bool binitialowner, // initial owner
Lptstr lpname // Object Name
);
This function is used to create an exclusive resource. The first parameter is not used and can be set to null. The second parameter specifies whether the resource is initially created by the process, the third parameter specifies the Resource Name.
Handle hmutex = createmutex (null, true, "screen ");
This statement creates a resource named screen and belongs to the process that created it.

Bool releasemutex (
Handle hmutex // handle to mutex
);
This function is used to release an exclusive resource. Once a process releases the resource, the resource will no longer belong to it. If you want to use the resource again, you need to apply for it again. The function for applying for resources is as follows: DWORD waitforsingleobject (
Handle hhandle, // handle to object
DWORD dwmilliseconds // time-out interval
);
The first parameter specifies the handle of the requested resource, and the second parameter is generally set to infinite, indicating that if the requested resource is not applied, it will wait for the resource. If it is set to 0, it indicates that the system will return if no resource is available. You can also specify how long it will wait to return, in the unit of 1‰ seconds. Now, it's time for us to solve the eg2 problem. We can make some modifications to eg2, as shown below:
Eg5:

# Include <iostream>
# Include <windows. h>
Using namespace STD;
Handle hmutex;
DWORD winapi fun (lpvoid lpparamter)
{

While (1 ){
Waitforsingleobject (hmutex, infinite );
Cout <"Fun display! "<Endl;
Sleep (1000 );
Releasemutex (hmutex );
}
} Int main ()
{
Handle hthread = createthread (null, 0, fun, null, 0, null );
Hmutex = createmutex (null, false, null );
Closehandle (hthread );
While (1 ){
Waitforsingleobject (hmutex, infinite );
Cout <"main display! "<Endl;
Sleep (2000 );
Releasemutex (hmutex );
}
Return 0;
}
Run the code as we expected to output the content we want to output.

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.