A simple example of C + + multithreaded programming

Source: Internet
Author: User

"Reprint": http://hi.baidu.com/xiandanshiyi/item/3ad6e1e567fc67324cdcaf53

C + + itself does not provide any multithreading mechanism, but under Windows, we can invoke the SDK Win32 API to write multithreaded programs, and here is a brief talk about:

Create a thread's function

1 HANDLE CreateThread (2 3Lpsecurity_attributes Lpthreadattributes,//SD4 5size_t Dwstacksize,//Initial Stack size6 7Lpthread_start_routine Lpstartaddress,//thread function8 9LPVOID Lpparameter,//thread ArgumentTen  OneDWORD dwCreationFlags,//creation Option A  -Lpdword Lpthreadid//thread identifier -  the);

  

Here we use only the third and fourth arguments, the third argument passes the address of a function, the new thread we want to specify, and the fourth parameter is the parameter pointer to the new thread.

EG1:

1#include <iostream>2 3#include <windows.h>4 5 using namespacestd;6 7  8 9 DWORD WINAPI Fun (lpvoid lpparamter)Ten  One { A  -        while(1) {cout<<"Fun display!"<<Endl;} -  the } -  -   -  + intMain () -  + { A  atHANDLE hthread = CreateThread (NULL,0, Fun, NULL,0, NULL); -  - CloseHandle (hthread); -  -      while(1) {cout<<"Main display!"<<Endl; } -  in     return 0; -  to}

We can see that the main thread (main function) and our own thread (fun function) are randomly executed alternately, but two threads output too fast, making it difficult to see clearly that we can use the function

1 VOID Sleep (23     DWORD dwmilliseconds   //  sleeptime45 );

To pause the execution of the thread, dwmilliseconds represents 1 per thousand seconds, so

1 Sleep (+);

Represents a pause of 1 seconds

EG2:

1#include <iostream>2 3#include <windows.h>4 5 using namespacestd;6 7  8 9 DWORD WINAPI Fun (lpvoid lpparamter)Ten  One {     A  -        while(1) {cout<<"Fun display!"<<endl; Sleep ( +);} -  the } -  -   -  + intMain () -  + { A  atHANDLE hthread = CreateThread (NULL,0, Fun, NULL,0, NULL); -  - CloseHandle (hthread); -  -        while(1) {cout<<"Main display!"<<endl; Sleep ( -);} -  in       return 0; -  to}

Executing the above code, this time we can clearly see the interleaved output of the fun display! and main display! on the screen, we find that these two functions are actually running concurrently, The attentive reader may find that our program will output line breaks whenever the fun function and main function output, but we see that there is a time when the program output is wrapped, and sometimes there is no output line break, or even a two line break. What's going on? Now let's change the program to see:

EG3:

1#include <iostream>2 3#include <windows.h>4 5 using namespacestd;6 7  8 9 DWORD WINAPI Fun (lpvoid lpparamter)Ten  One { A  -        while(1) {cout<<"Fun display!\n"; Sleep ( +);} -  the } -  -   -  + intMain () -  + { A  atHANDLE hthread = CreateThread (NULL,0, Fun, NULL,0, NULL); -  - CloseHandle (hthread); -  -        while(1) {cout<<"Main display!\n"; Sleep ( -);} -  in       return 0; -  to}

We run this program again and we find that this time, as we expected, correctly outputs what we want to output and the format is correct. Let's talk about why our program didn't run correctly before. Multi-threaded programs run concurrently, and if some resources are shared between multiple threads, we cannot guarantee that these resources will be properly exploited, because resources are not exclusive at this time, for example:

EG4:

Join has a resource int a = 3

There is a thread function selfadd () that function is to make a + = A;

There is also a thread function selfsub () that function is to make a-= A;

We assume that the above two threads are in parallel, if Selfadd is executing, we want to have a programming 6, but at this point Selfsub get the chance to run, so a becomes 0, wait until Selfadd to execute the opportunity, a + = A, but at this time a is 0, Not as we expected to 6, we go back to the front EG2, here, we can see the screen as a resource, this resource is shared by two threads, added when the fun function output fun display!, will be output endl (that is, empty buffer and newline, Here we can not understand what the buffer is, but at this point the main function does get the chance to run, when the fun function has not time to output a newline to the CPU to the main function, and then the main function directly after the fun display! output main display!, As for why sometimes the program will output two consecutive lines, the reader can use the same analysis method to analyze, here I do not speak more, left to the reader to think.

So why do we change EG2 to EG3 and run it right? The reason is that while multiple threads are running concurrently, there are some operations that must be one go and not allowed to break, so we see that the results of EG2 and EG3 are not the same.

So, is not the EG2 code we can not let it run correctly? The answer is, of course, I'll tell you how to get the EG2 code to work correctly. This involves multi-threaded synchronization issues. For a resource to be pooled by multiple threads can cause confusion in the program, our workaround is to allow only one thread to have exclusive access to the shared resource, which will solve the problem above.

1 HANDLE CreateMutex (23     Lpsecurity_attributes lpmutexattributes,  //  SD45     BOOL Binitialowner,                       //  initial owner67     LPCTSTR lpname                            //  object name89  );

The function is used to create an exclusive resource, the first parameter we do not use, can be set to NULL, the second parameter specifies whether the resource is initially attributed to the process that created it, and the third parameter specifies the name of the resource.

1 HANDLE Hmutex = CreateMutex (null,true,"screen"

This statement creates a resource called screen and belongs to the process that created it

1 BOOL ReleaseMutex (23     HANDLE Hmutex   //  HANDLE to mutex45   );

The function is used to free an exclusive resource, and once the process releases the resource, the resource is no longer part of it, and if it is used again, it needs to be re-requested. The functions for requesting resources are as follows

1 DWORD WaitForSingleObject (23     HANDLE Hhandle,        //  HANDLE to Object45     DWORD dwmilliseconds   / /  time-out interval67   );

The first parameter specifies the handle of the requested resource, and the second parameter is generally specified as infinite, which means that if the resource is not requested, it is waiting for the resource if it is specified as 0, indicating that once the resource is not available, it can also specify how long to wait before returning, in 1 per thousand seconds. Well, it's time for us to solve the EG2 problem, we can make some changes to EG2, as follows

EG5:

1#include <iostream>2 3#include <windows.h>4 5 using namespacestd;6 7 HANDLE Hmutex;8 9 DWORD WINAPI Fun (lpvoid lpparamter)Ten  One { A  -          -  the         while(1) {  -  - WaitForSingleObject (Hmutex, INFINITE); -  +cout<<"Fun display!"<<Endl; -  +Sleep ( +); A  at ReleaseMutex (Hmutex); -  -         } -  -   } -  in   -  to intMain () +  - { the  *HANDLE hthread = CreateThread (NULL,0, Fun, NULL,0, NULL); $ Panax NotoginsengHmutex = CreateMutex (NULL, FALSE," Screen"); -  the CloseHandle (hthread); +  A        while(1) { the  + WaitForSingleObject (Hmutex, INFINITE); -  $cout<<"Main display!"<<Endl;  $  -Sleep ( -); -  the ReleaseMutex (Hmutex); - Wuyi       } the  -       return 0; Wu  -}

Run the code as we expect the content of the output.

A simple example of C + + multithreaded programming

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.