设为首页 加入收藏

TOP

初探C++11 Thread
2015-07-20 18:06:36 来源: 作者: 【 】 浏览:11
Tags:初探 Thread

Thread

开启一个线程

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

#include
  
   
#include
   
     using namespace std; void hello() { cout<<"hello kitty"<
     
     


输出结果:

\


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

#include
      
       
#include
       
         using namespace std; class Say_hello { public: void operator()(){cout<<"hello";} }; int main() { Say_hello hello; std::thread t(hello); t.join(); return 0; }
       
      

输出结果:

\

带参数的函数

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

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

比如说下面这2个例子

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


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

\


带参数时,输出结果为:

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


\

锁的实现

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

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

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

#include
          
           
#include
           
             #include
            
              using namespace std; int tickets_count = 10; mutex a_mutex; void sale() { lock_guard
             
               guard(a_mutex); //a_mutex.lock(); while(tickets_count>0) { cout<
               
               

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

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

输出结果为:

\



】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇UVa 11732 strcmp() Anyone? 下一篇Codeforces Round #256 (Div. 2/B..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: