开发者社区> 问答> 正文

C++11 并发有关启动线程这方面的教程

C++11 引入一个全新的线程库,包含启动和管理线程的工具,提供了同步(互斥、锁和原子变量)的方法,我将试图为你介绍这个全新的线程库。

如果你要编译本文中的代码,你至少需要一个支持 C++11 的编译器,我使用的是 GCC 4.6.1,需要使用 -c++0x 或者 -c++11 参数来启用 C++11 的支持。

展开
收起
a123456678 2016-03-04 10:08:15 2130 0
1 条回答
写回答
取消 提交回答
  • 启动线程

    在 C++11 中启动一个线程是非常简单的,你可以使用 std:thread 来创建一个线程实例,创建完会自动启动,只需要给它传递一个要执行函数的指针即可,请看下面这个 Hello world 代码:

    #include <thread>
    #include <iostream>
      
    void hello(){
        std::cout << "Hello from thread " << std::endl;
    }
      
    int main(){
        std::thread t1(hello);
        t1.join();
      
        return 0;
    }

    所有跟线程相关的方法都在 thread 这个头文件中定义,比较有意思的是我们在上面的代码调用了 join() 函数,其目的是强迫主线程等待线程执行结束后才退出。如果你没写 join() 这行代码,可能执行的结果是打印了 Hello from thread 和一个新行,也可能没有新行。因为主线程可能在线程执行完毕之前就返回了。
    线程标识

    每个线程都有一个唯一的 ID 以识别不同的线程,std:thread 类有一个 get_id() 方法返回对应线程的唯一编号,你可以通过 std::this_thread 来访问当前线程实例,下面的例子演示如何使用这个 id:

    #include <thread>
    #include <iostream>
    #include <vector>
      
    void hello(){
        std::cout << "Hello from thread " << std::this_thread::get_id() << std::endl;
    }
      
    int main(){
        std::vector<std::thread> threads;
      
        for(int i = 0; i < 5; ++i){
            threads.push_back(std::thread(hello));
        }
      
        for(auto& thread : threads){
            thread.join();
        }
      
        return 0;
    }

    依次启动每个线程,然后把它们保存到一个 vector 容器中,程序执行结果是不可预测的,例如:
    Hello from thread 140276650997504
    Hello from thread 140276667782912
    Hello from thread 140276659390208
    Hello from thread 140276642604800
    Hello from thread 140276676175616

    也可能是:

    Hello from thread Hello from thread Hello from thread 139810974787328Hello from thread 139810983180032Hello from thread
    139810966394624
    139810991572736
    139810958001920

    或者其他结果,因为多个线程的执行是交错的。你完全没有办法去控制线程的执行顺序(否则那还要线程干吗?)

    使用 lambda 启动线程
    当线程要执行的代码就一点点,你没必要专门为之创建一个函数,你可以使用 lambda 来定义要执行的代码,因此第一个例子我们可以改写为:

    #include <thread>
    #include <iostream>
    #include <vector>
      
    int main(){
        std::vector<std::thread> threads;
      
        for(int i = 0; i < 5; ++i){
            threads.push_back(std::thread([](){
                std::cout << "Hello from thread " << std::this_thread::get_id() << std::endl;
            }));
        }
      
        for(auto& thread : threads){
            thread.join();
        }
      
        return 0;
    }
    2019-07-17 18:51:52
    赞同 展开评论 打赏
问答分类:
问答地址:
相关产品:
问答排行榜
最热
最新

相关电子书

更多
使用C++11开发PHP7扩展 立即下载
GPON Class C++ SFP O;T Transce 立即下载
GPON Class C++ SFP OLT Transce 立即下载

相关实验场景

更多