C++11多线程编程之初步介绍

8 篇文章 2 订阅

前言:我认为作为一名C++程序员掌握多线程编程还是很有好处的,在C++11出来之后,有一个std::thread库可以供我们使用,来编写多线程程序;


首先我们需要了解C++11中多线程编程需要涉及的标准库

与C++11多线程相关的头文件

C++11新标准一共提供了五个标准库来支持多线程编程,分别是<thread>,<atomic>,<mutex>,<conditinon_variable>and<future>

    <thread>:主要声明了std::thread类

    <atomic>:主要声明了两个类,std::atomic和std::atomic_flag   

   <mutex>:主要声明了与互斥量(mutex)相关的类,包括std::mutex,std::lock_guard,std::unique_lock等

   <condition_variable>:主要声明了与条件变量相关的类,包括std::condition_variable和std::condition_variable_any

  <future>:主要声明std::promise,std::package_task两个Provider类,以及std::future和std::share_future两个Future类

使用thread类的例子

#include <iostream> // std::cout
#include <thread>   // std::thread

void thread_task() {
    std::cout << "hello thread" << std::endl;
}

int main(int argc, const char *argv[])
{
    std::thread t(thread_task);
    t.join();

    return EXIT_SUCCESS;
}  


std::thread构造函数

defaultthread() noexcept;
initialization
template <class Fn, class... Args>
explicit thread (Fn&& fn, Args&&... args);
copythread(const thread&)=delete
movethread(thread&&  T) noexcept;

1、默认构造函数,构造一个空的thread对象

2、初始化构造函数,创建一个thread对象,该对象可以被joinable,新产生的线程会调用fn函数,该函数的参数由args给出

3、拷贝构造函数被禁用,意思是thread不能被拷贝构造

4、move构造函数

可被joinable的对象必须在销毁之前jion主线程或者被detached

thread构造函数使用的例子

#include <iostream>
#include <utility>
#include <thread>
#include <chrono>
#include <functional>
#include <atomic>
 
void f1(int n)
{
    for (int i = 0; i < 5; ++i) {
        std::cout << "Thread 1 executing\n";
        ++n;
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }
}
 
void f2(int& n)
{
    for (int i = 0; i < 5; ++i) {
        std::cout << "Thread 2 executing\n";
        ++n;
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }
}
 
int main()
{
    int n = 0;
    std::thread t1; // t1 is not a thread
    std::thread t2(f1, n + 1); // pass by value
    std::thread t3(f2, std::ref(n)); // pass by reference
    std::thread t4(std::move(t3)); // t4 is now running f2(). t3 is no longer a thread
    t2.join();
    t4.join();
    std::cout << "Final value of n is " << n << '\n';
}

注意:t2里面的n+1是f1的参数,为值传递;t3里面的是引用传递需要使用std::ref()函数

可能的结果:

Thread 1 executing
Thread 2 executing
Thread 1 executing
Thread 2 executing
Thread 1 executing
Thread 2 executing
Thread 1 executing
Thread 2 executing
Thread 2 executing
Thread 1 executing
Final value of n is 5

move复制操作

movethread& operator=(thread&& T) noexcept;
copythread& operator=(const thread&)=delete;


  





其他常用相关函数

get_id()获取线程编号
joinable()判断是否可以join
join()加入线程
detach()分离线程
swap()交换线程
native_handle()返回native_handle
  
  

注意:detach()是将本线程分离出去,允许本线程单独执行,但是当主线程结束的时候,分离出去的子线程有没有结束都会被强制kill

未完待续。。。。。。。。。。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值