zoukankan      html  css  js  c++  java
  • C++ 并发编程1

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

    #include <iostream>

    #include <thread>

    using namespace std;

    void hello(){

      cout << "Hello Concurrent World ";

    }

    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()}

  • 相关阅读:
    CF1270H. Number of Components
    NOI Online Round2划水记
    uoj#247. 【Rujia Liu's Present 7】Mysterious Space Station口胡
    mysql习题
    MySQL基础
    python网络编程(进程与多线程)
    xshell连接虚拟机Ubuntu问题
    python来写打飞机
    timeit模块
    python常用模块
  • 原文地址:https://www.cnblogs.com/daibigmonster/p/7832579.html
Copyright © 2011-2022 走看看