码迷,mamicode.com
首页 > 编程语言 > 详细

C++11多线程初体验

时间:2015-05-18 18:57:50      阅读:103      评论:0      收藏:0      [点我收藏+]

标签:多线程

在C++11标准之前,使用C++编写多线程程序要么需要第三方的API如pthread,要么需要依赖运行平台提供的API,使用起来很不方便。而C++11提供了平台无关的语言级别的支持,这极大得方便了我们开发人员。

C++11的多线程支持主要通过使用如下的头文件中的类或者函数:<atomic><thread><mutex><condition_variable><future>。


新建线程

通过std::thread类新建线程。一般有两种方式:
1) 传递一个函数(可以是函数指针或者Lambda表达式等)
2) 传递一个对象,该对象重载了操作符(),也可以说该对象中必须有一个名为operator()的函数。

下面看实例(Visual Studio 2015运行通过):

#include <thread>
#include <iostream>

using namespace std;

// 一个普通的函数
void fun(int num)
{
    cout << "The function child thread begin...\n";
    cout << "I come from function fun(): " << num << ‘\n‘;
    cout << "The function child thread end...\n";
    cout << endl;
}

// 一个函数类,实现了operator()方法
class Fun
{
public:
    void operator()(int num)
    {
        cout << "The class child thread begin...\n";
        cout << "I come from class Fun: " << num << ‘\n‘;
        cout << "The class child thread end...\n";
        cout << endl;
    }
};

int main()
{
    cout << "Main thread begin..." << ‘\n‘;
    cout.sync_with_stdio(true); // 设置输入流cout是线程安全的
    thread t_1(fun, 1); // 新建线程,第一个参数是函数指针,第二个参数是函数的参数(第二个参数是可变长参数)
    t_1.join(); // join方法数会阻塞主线程直到目标线程调用完毕,即join会直接执行该子线程的函数体部分
    thread t_2(fun, 2);
    t_2.detach(); // detach方法不会阻塞任何线程,目标线程就成为了守护线程,驻留后台运行
    Fun oFun;
    thread t_3(ref(oFun), 3); //这里新建线程,使用对象进行初始化,这里的通过ref传递的是oFun本身而不是其拷贝
    t_3.join();
    cout << "Main thread end..." << endl;
    return 0;
}

运行结果:
技术分享

可以看到先执行主线程,然后是t_1子线程,然后是t_2子线程,但是t_2子线程没有执行完毕,又开始执行t_3子线程,等t_3执行完毕,接着执行t_2,然后是结束主线程。
为什么会是这样的结果呢?因为t_1和t_3调用的是thread的join方法,而t_2调用的是detach方法。
join()等待该子线程执行完之后,主线程才可以继续执行下去,此时主线程会释放掉执行完后的子线程资源。而detach()将子线程从主线程里分离,成为一个后台线程,子线程执行完成后会自己释放掉资源。分离后的线程,主线程将对它没有控制权了。


线程同步问题

一提到线程,一定会有资源竞争,以及死锁活锁的问题。
C++中提供atomic保持变量的原子性,个人感觉有些类似于Java和C#中的volatile关键字。
下面看这样一个例子:

#include <thread>
#include <iostream>
#include <vector>

using namespace std;

void func(int& counter)
{
    for (int i = 0; i < 100000; ++i)
    {
        ++counter;
    }
}

int main()
{
    int counter = 0;
    vector<thread> threads;
    for (int i = 0; i < 10; ++i)
    {
        threads.push_back(thread(func, ref(counter)));
    }
    for (auto& current_thread : threads)
    {
        current_thread.join();
    }
    cout << "Result = " << counter << ‘\n‘;
    return 0;
}

你多执行几次,会发现每次输出的counter的值并不总是1000000(100000*10=1000000,10个线程,每个线程每次增加100000),为什么呢?这就涉及到多线程中资源的竞争问题。
那么如何解决这个问题呢?C++中提供了atomic类,看修改后的程序:

#include <thread>
#include <iostream>
#include <vector>
#include <atomic>

using namespace std;

void func(atomic<int>& counter)
{
    for (int i = 0; i < 100000; ++i)
    {
        ++counter;
    }
}

int main()
{
    atomic<int> counter(0);
    vector<thread> threads;
    for (int i = 0; i < 10; ++i)
    {
        threads.push_back(thread(func, ref(counter)));
    }
    for (auto& current_thread : threads)
    {
        current_thread.join();
    }
    cout << "Result = " << counter << ‘\n‘;
    return 0;
}

这样执行上面程序不管多少次输出总是:Result = 1000000
此外,atomic类还提供了封装好的一些函数操作,详见:C++参考-atomic

初始C++多线程,就写到这里。

C++11多线程初体验

标签:多线程

原文地址:http://blog.csdn.net/theonegis/article/details/45824359

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!