C + + multithreaded programming Simple example _c language

Source: Internet
Author: User
Tags sleep

C + + itself does not provide any multithreaded mechanisms, but under Windows, we can invoke the SDK Win32 API to write multithreaded programs, and here's a quick way to say this:

Creating a thread's function

Copy Code code as follows:

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 use only the third and fourth arguments, the third parameter 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:

Copy Code code as follows:

#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 (the main function) and our own threads (the fun function) are randomly alternating, but the two-thread output is too fast, making it hard to see that we can use the function

Copy Code code as follows:

VOID Sleep (
DWORD dwmilliseconds//Sleep time
);

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

Sleep (1000);

Indicates a pause of 1 seconds

EG2:

Copy Code code as follows:

#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;
}

By executing the above code, we can clearly see that the fun display! and main display! are interleaved on the screen, and we find that these two functions do run concurrently. Careful readers may find that our program is every time the fun function and the main function output will be output line, but we see that there is indeed some time the output of the program, sometimes there is no output line, and sometimes the output of two lines. What's going on? Now let's change the program to see:

EG3:

Copy Code code as follows:

#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;
}

We ran the program again, and we found that at this point, as we expected, we correctly output what we want to output and the format is correct. Let me just tell you 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 used correctly because resources are not exclusive at this time, for example:

EG4:

Join has a resource int a = 3

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

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

Let's assume that the top two threads are concurrent. If Selfadd is executing, our goal is to let a programming 6, but at this time selfsub get the opportunity to run, so A is a 0, wait until Selfadd to execute the opportunity, a + a, but at this time a is indeed 0, And not as we expected. To 6, we go back to the front EG2, where we can look at the screen as a resource that is shared by two threads, adding that when the fun function outputs the fun display!, it will output Endl (that is, emptying the buffer and wrapping it. Here we can not understand what the buffer, but at this time the main function has been the opportunity to run, at this time the fun function has not been able to output line to the CPU to the main function, and then the main function directly in 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 will not say more, leaving the reader to think for themselves.

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

So, is not EG2 code we can not let it run correctly? The answer is, of course, I'll tell you how to make EG2 code work correctly. This involves multithreading of synchronization issues. For a resource to be shared by multiple threads can cause chaos in the program, our solution is to allow only one thread to have the exclusive of shared resources, so that the problem can be solved.

Copy Code code as follows:

HANDLE CreateMutex (
Lpsecurity_attributes lpmutexattributes,//SD
BOOL Binitialowner,//initial owner
LPCTSTR lpname//object name
);

This 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 initially belongs to the process that created it, and the third parameter specifies the name of the resource.

Copy Code code as follows:

HANDLE Hmutex = CreateMutex (null,true, "screen");

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

Copy Code code as follows:

BOOL ReleaseMutex (
HANDLE Hmutex//HANDLE to Mutex
);

This function frees an exclusive resource, and once the process releases the resource, it no longer belongs to it, and if it is to be used, it needs to be requested to reapply for that resource. The function of the request resource is as follows

Copy Code code as follows:

DWORD WaitForSingleObject (
HANDLE Hhandle,//HANDLE to Object
DWORD dwmilliseconds//time-out interval
);

The first parameter specifies the handle to the requested resource. The second parameter is generally specified as infinite, which means that if you wait for the resource without applying to the resource, if you specify 0, it means that once the resource is not returned, you can 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:

Copy Code code as follows:

#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, "screen");
CloseHandle (Hthread);
while (1) {
WaitForSingleObject (Hmutex, INFINITE);
cout<< "Main display!" <<endl;
Sleep (2000);
ReleaseMutex (Hmutex);
}
return 0;
}

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

The above mentioned is the entire content of this article, I hope you can enjoy.

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.