C++ 并发编程1

一个简单的并发编程的举例

#include <iostream>

#include <thread>

using namespace std;

void hello(){

  cout << "Hello Concurrent World\n";

}

int main(){

  thread t(hello);

  t.join();

  return 0;

}

编译指令为g++ -o test <C++文件名> -std=c++11 -lpthread

头文件thread,管理线程和类在<thread>中声明。

其次,打印信息的代码被移动到了一个独立的函数hello中,因为每个线程都必须具有一个初始函数,线程的执行从这里开始。在上面的例子中线程std::thread的对象拥有新函数hello()作为其初始函数。

第三,join()函数是等所有线程结束,然后结束初始进程结束,如果没有这个函数,将导致进程混乱。这个时候两种处理方式。

1等待线程完成,则是t.join();

2让线程继续工作,初始线程结束,这需要将线程分离,所以就要用t.detach()

 

注意点:

1、注意声明:std::thread my_thread(background_task())

这里相当于声明了一个名为my_thread的函数,这个函数带有一个参数(函数指针指向没有参数并返回background_task对象的函数),返回一个std::thread对象的函数,而不是启动了一个线程

要是启动线程,则有下面两种方式

thread my_thread((background_task()));

thread my_thread{background_task()}

 

posted @ 2017-11-14 20:05  戴怪兽  阅读(175)  评论(0编辑  收藏  举报