C++ 中的多线程

在VS2015中,创建多线程很方便,只需要引入相应的头文件即可

其中 #include <thread> 为多线程需要的头文件。

引入头文件后,即可创建子线程进行耗时操作了。

当然,为了防止变量共享带来的问题,可以加入互斥操作,这时需要引入相应的互斥操作的头文件,如:mutex。

关于多线程的互斥,可以参考:http://www.cnblogs.com/haippy/p/3237213.html 写的很详细。

一个简单的例子:

//C++ 多线程示例

#include "stdafx.h"
#include <iostream>
#include <string>
#include <thread>
#include <mutex>
using namespace std;


mutex mutx;

//一个全局函数,将会在线程中调用
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 < 1000; i++)
    {
        printHreadInfro(101,par);
    }
}
void sayHello_2(string par)
{
    for (int i = 0; i < 1000; i++)
    {
        printHreadInfro(2001,par);
    }
}
int main()
{
    thread th1(sayHello,"par in id1");    //定义线程时可以给回调函数传递任意多的任意类型的参数(定义函数时的参数列表)
    th1.join();                    //通过join阻塞线程,直到该线程结束
    thread th2(sayHello_2,"hello, i'm from thread 2");
    th2.detach();                //如果可分离,则可以用 detach 将子线程与主线程分离

    string s;
    getline(cin, s, '\n');
    return 0;
}

由于使用 th1.join()使线程阻塞,只有当th1执行完毕后,才会往下继续执行,此时可以不考虑互斥问题,但如果不阻塞线程1、2,则需要考虑互斥问题。

原文地址:https://www.cnblogs.com/xtblog/p/5738648.html