美文网首页
c++ multithread and lock--part 1

c++ multithread and lock--part 1

作者: 前进中的奋斗猿 | 来源:发表于2019-11-12 22:28 被阅读0次

    I am planning to write a serials articles on multithread and locks of c++, including but not limited to the usage and principles about them. This work will be started from tonight,i.e. the night of Nov. 12, 2019.

    一、多线程编程的优势

    线程是能够独立调度的基本单位。在多线程编程出来之前,程序只能以单线程的模式运行,这意味着程序中的所有逻辑都只能串行执行。在这种情况下,如果程序中某一段逻辑比如文件加载、网络请求等比较耗时,那么程序中的后续逻辑会长时间处于阻塞状态而得不到执行,导致整个程序执行效率不高。多线程开发其实就是利用cpu多核的特点,将程序中的工作量分成多个子task,将数据没有直接相关性的task分配到不同的核上同时运行,从而达到并行执行的目的,如此,程序的运行效率可得到明显提升。

    二、c++多线程中如何使用多线程

    c++11中提供了thread库以及一套封装好的并发编程方法,我们常用的库主要有:

    • <thread>包含std::thread类以及std::this_thread命名空间。
    • <atomic>包含std::atomic和std::atomic_flag类,以及一套c风格的院子类型和与c兼容的院子操作的函数。
    • <mutex>包含于互斥量相关的类以及其他类型和函数。
    • <future>包含连个Provider类(std::promise和std::package_task)和两个Future类(std::future和std::shared_future)以及相关的类型和函数。
    • <condition_variable>包含与条件变量相关的类,包括std::condition_variable和std::condition_variable_any。
      在后面的文章中将对上述库的使用进行详细的介绍。我们这一系列的文章都将基于c++11及以后的版本编写用例代码。用c++编写多线程很简单 :
    #include <iostream>
    #include <thread>
    
    #define PRINT(X)        \
       void print##X() {   \
           std::cout << " thread " << X << " is running " << std::endl; \
       }
    PRINT(1)
    PRINT(2)
    PRINT(3)
    PRINT(4)
    PRINT(5)
    PRINT(6)
    
    int main() {
       std::thread t1(print1);
       std::thread t2(print2);
       std::thread t3(print3);
       std::thread t4(print4);
       std::thread t5(print5);
       std::thread t6(print6);
       t1.detach();
       t2.detach();
       t3.detach();
       std::cout << "---- main thread print 1th stage ---" << std::endl;
       t4.join();
       t5.join();
       t6.join();
       std::cout << "---- main thread print 2th stage ---" << std::endl;
       return 0;
    }
    

    注意到在代码中我使用了两种方式来启用线程,一种是join(),一种是detach()。join是一个阻塞函数,代表父线程跟子线程采用同步方式运行,也就是说只有当子线程运行完后父线程才会继续往后执行。而detach是非阻塞函数,父线程不用等到子线程执行完毕即可继续往后执行。

    相关文章

      网友评论

          本文标题:c++ multithread and lock--part 1

          本文链接:https://www.haomeiwen.com/subject/dldcictx.html