In VS2015, it is convenient to create multithreading, just introduce the corresponding header file to
where #include <thread> header files are required for multithreading.
Once the header file is introduced, the child threads can be created for time-consuming operations.
Of course, in order to prevent the problem of variable sharing, you can join the mutex operation, you need to introduce the corresponding mutually exclusive operation of the header file, such as: mutex.
On the mutual exclusion of multithreading, you can refer to:http://www.cnblogs.com/haippy/p/3237213.html written in very detailed.
A simple example:
C + + Multithreading sample
#include "stdafx.h"
#include <iostream>
#include <string>
#include <thread>
#include <mutex>
using namespace Std;
Mutex Mutx;
A global function that will be called in the thread
void Printhreadinfro (int id,string par) {
Mutx.lock ();
if (Mutx.try_lock ())
{
cout << Endl << "used by thread:" << ID << "; par = "<< par << Endl;
Mutx.unlock ();
}
Mutx.unlock ();
}
void SayHello (string par) {
for (int i = 0; i <; i++)
{
Printhreadinfro (101,par);
}
}
void Sayhello_2 (string par)
{
for (int i = 0; i <; i++)
{
Printhreadinfro (2001,par);
}
}
int main ()
{
Thread Th1 (SayHello, "par in id1"); You can pass any number of arguments of any type to the callback function when you define the thread (the parameter list when the function is defined)
Th1.join (); Blocks a thread through a join until the thread ends
Thread Th2 (sayhello_2, "Hello, I ' m from Thread 2");
Th2.detach (); If separable, you can detach the child thread from the main thread with detach
string S;
Getline (CIN, S, ' \ n ');
return 0;
}
Because the thread is blocked by using Th1.join (), the execution continues only when the Th1 has finished executing, regardless of the mutex, but if you do not block threads 1, 2, you need to consider mutex issues.
Multithreading in C + +