Multithreading in C + +

Source: Internet
Author: User

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 + +

Related Article

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.