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

初探C++11 Thread

时间:2014-07-18 23:03:18      阅读:343      评论:0      收藏:0      [点我收藏+]

标签:c++   c++11   线程初步   多线程   线程安全   

Thread

 

开启一个线程

 

使用c++11开启一个线程是比较简单的,如下:

 

#include<iostream>
#include<thread>
using namespace std;

void hello()
{
    cout<<"hello kitty"<<endl;
}

int main()
{
    std::thread t(hello);
     t.join();
     return 0;
}


输出结果:

bubuko.com,布布扣

 

 

 

 


 

也可以通过函数对象的方式

 

#include<iostream>
#include<thread>
using namespace std;


class Say_hello
{
public:
    void operator()(){cout<<"hello";}
};


int main()
{
    Say_hello hello;
    std::thread t(hello);
    t.join();
    return 0;
}

输出结果:

bubuko.com,布布扣

 

 

 

带参数的函数

 

当函数自身有参数时,形参可以直接写在开启线程的函数参数的后面,如:

thread  t( function , t1 , t2 , ...)

比如说下面这2个例子

 

#include<iostream>
#include<thread>
using namespace std;


class Say_hello
{
public:
    enum {times = 2};
    void operator()(int n = times)
    {
        for(int i=0;i!=n;i++)
            cout<<"hello"<<endl;
    }
};


int main()
{
    Say_hello hello;
    std::thread t(hello);
    t.join();
    return 0;
}


不带参数时,输出结果为:

bubuko.com,布布扣


 

 

 

带参数时,输出结果为:

int main()
{
    Say_hello hello;
    std::thread t(hello,5);
    t.join();
    return 0;
}


bubuko.com,布布扣

 

 

 

锁的实现

 

 

多线程为了实现线程安全,当访问共享数据时,要避免几个线程同时访问,以免造成竞争条件(race condition)

下面举了一个简单的例子,用锁来实现同步。

 

 

 

一共10张票,开4个线程来卖票。

 

#include<iostream>
#include<thread>
#include<mutex>
using namespace std;

int tickets_count = 10;
mutex a_mutex;

void sale()
{
    lock_guard<mutex> guard(a_mutex);
    //a_mutex.lock();
    while(tickets_count>0)
    {
       cout<<tickets_count--<<endl;
    }
     //a_mutex.unlock();
}

int main()
{
    std::thread t1(sale);
    std::thread t2(sale);
    std::thread t3(sale);
    std::thread t4(sale);
    t1.join();
    t2.join();
    t3.join();
    t4.join();
    return 0;
}

如果不加锁,可能造成重复,输出混乱(std::out 也不是线程安全)

通过对临界区加锁来尽量实现线程安全。

 

输出结果为:

bubuko.com,布布扣


 

 

 


 

 

初探C++11 Thread,布布扣,bubuko.com

初探C++11 Thread

标签:c++   c++11   线程初步   多线程   线程安全   

原文地址:http://blog.csdn.net/wangxiaobupt/article/details/37883445

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