C++并发与多线程(五)互斥量,atomic、与线程池(下)

简介: C++并发与多线程(五)互斥量,atomic、与线程池(下)
  1. 如果用std::launch::async来调用async
#include <iostream>
#include <mutex>
#include <thread>
#include <future>
using namespace std;
std::atomic<int> g_count;
int mythread() {
    cout << "thread start thread id is: " << std::this_thread::get_id() << endl;
    return 10;
}
int main() {
    cout << "main start thread id is: " << std::this_thread::get_id() << endl;
    std::future<int> res = std::async(std::launch::async,mythread);
    cout << "res.get() is : " << res.get() << endl;
}

  程序输出结果为:

main start thread id is: 0x1000e3d40
res.get() is : thread start thread id is: 0x16fe87000
10

  强制这个异步任务在新线程上执行,这意味着,系统必须要创建出新线程来运行入口函数。

  1. 如果同时用std::launch::async | std::launch::deferred
#include <iostream>
#include <mutex>
#include <thread>
#include <future>
using namespace std;
std::atomic<int> g_count;
int mythread() {
    cout << "thread start thread id is: " << std::this_thread::get_id() << endl;
    return 10;
}
int main() {
    cout << "main start thread id is: " << std::this_thread::get_id() << endl;
    std::future<int> res = std::async(std::launch::async | std::launch::deferred,mythread);
    cout << "res.get() is : " << res.get() << endl;
}

  这里这个或者关系意味着async的行为可能是std::launch::async创建新线程立即执行, 也可能是 std::launch::deferred没有创建新线程并且延迟到调用get()执行,由系统根据实际情况来决定采取哪种方案。

  1. 不带额外参数std::async(mythread),只给async一个入口函数名,此时的系统给的默认值是 std::launch::async | std::launch::deferred3.一样,有系统自行决定异步还是同步运行。

  async的这种不确定性问题,不确定是否会创建出新线程的话,如何来解决呢。不加额外参数的async调用时让系统自行决定,是否创建新线程。


std::future result = std::async(mythread);

  这个问题焦点在于,上述这种写法,任务到底有没有被推迟执行。我们可以通过wait_for返回状态来判断:

#include <iostream>
#include <mutex>
#include <thread>
#include <future>
using namespace std;
std::atomic<int> g_count;
int mythread() {
    cout << "thread start thread id is: " << std::this_thread::get_id() << endl;
    return 10;
}
int main() {
    cout << "main start thread id is: " << std::this_thread::get_id() << endl;
    std::future<int> res = std::async(mythread);
    std::future_status status = res.wait_for(std::chrono::seconds(0s));
    //std::future_status status = result.wait_for(6s);
        if (status == std::future_status::timeout) {
            //超时:表示线程还没有执行完
            cout << "超时了,线程还没有执行完" << endl;
        }
        else if (status == std::future_status::ready) {
            //表示线程成功放回
            cout << "线程执行成功,返回" << endl;
            cout << res.get() << endl;
        }
        else if (status == std::future_status::deferred) {
            cout << "线程延迟执行" << endl;
            cout << res.get() << endl; // 这个时候才去调用了mythread
        }
}

  程序输出结果为:

main start thread id is: 0x1000e7d40
超时了,线程还没有执行完
thread start thread id is: 0x16fe87000
Program ended with exit code: 0


atomic的原子操作


  来看如下代码:

#include <iostream>
#include <thread>
#include <list>
#include <mutex>
using namespace std;
class A {
public:
    A(){
        atm = 0;
    }
    void inMsgRecvQueue()
    {
        for(int i = 0; i < 10; ++i){
            ++atm;
        }
    }
    void outMsgRecvQueue()
    {
        while(true){
            cout << "automic is: " << atm << endl;
        }
    }
private:
    std::atomic<int> atm;
    list<int> msgRecvQueue;
    mutex myMutex;
    std::condition_variable cond;
};
int main()
{
    A myobja;
    thread myOutMsgObj(&A::outMsgRecvQueue, &myobja);
    thread myInMsgObj(&A::inMsgRecvQueue, &myobja);
    myOutMsgObj.join();
    myInMsgObj.join();
    return 0;
}


上述代码中的cout << atm << endl;并不是一个原子操作。因为只有读取atm是原子操作,但是cout输出的时候,有可能atm的值已经被改变掉了,导致最终显示在屏幕上的值是一个“曾经值”。

  如果在拷贝构造函数中,调用赋值语句的话,我们可以得到如下代码:


std::atomic<int> atm = 0;
auto atm2 = atm; //不可以

  

但是上述这种代码用来初始化是不可以的,会报错。但是可以通过load()函数来以原子方式读atomic对象的值。


atomic<int> atm2(atm.load());

  store()以原子方式写入内容:


atm2.store(12);

  原子操作实质上是:不允许在进行原子对象操作时进行CPU的上下文切换。


std::async和std::thread()区别:


  std::thread()如果系统资源紧张可能出现创建线程失败的情况,如果创建线程失败那么程序就可能崩溃,并且不容易拿到函数返回值(不是拿不到,通过设置全局变量可以拿到)。std::async()创建异步任务。可能创建线程也可能不创建线程,并且容易拿到线程入口函数的返回值。由于系统资源限制:

  1. 如果用std::thread创建的线程太多,则可能创建失败,系统报告异常,崩溃。
  2. 如果用std::async,一般就不会报异常。因为如果系统资源紧张,无法创建新线程的时候,async不加额外参数的调用方式就不会创建新线程。而是在后续调用get()请求结果时执行在这个调用get()的线程上。如果你强制async一定要创建新线程就要使用std::launch::async标记。承受的代价是,系统资源紧张时可能崩溃。
  3. 根据经验,一个程序中线程数量 不宜超过100~200


浅谈线程池


  假设我们有如下场景,场景设想:服务器程序, 每来一个客户端,就创建一个新线程为这个客户提供服务。我们需要考虑如下问题:

  1. 2万个玩家,不可能给每个玩家创建一个新线程,此程序写法在这种场景下不通。
  2. 程序稳定性问题:编写代码中,“时不时地突然”创建一个线程,这种写法,一般情况下不会出错,但是不稳定的;

  线程池:把一堆线程弄到一起,统一管理。这种统一管理调度,循环利用的方式,就叫做线程池。用的时候抓一个过来用,用完了之后把它放回线程池中去,也不释放。

  实现方式:程序启动时,一次性创建好一定数量的线程。这种方式让人更放心,觉得程序代码更稳定。

  • 线程创建数量谈
  1. 线程创建的数量极限的问题:一般来讲,2000个线程基本就是极限;再创建就会崩溃。
  2. 线程创建数量建议:采用某些计数开发程序提供的建议,遵照建议和指示来确保程序高效执行。
  3. 创建多线程完成业务;考虑可能被阻塞的线程数量,创建多余最大被阻塞线程数量的线程,如100个线程被阻塞再充值业务,开110个线程就是很合适的。
  4. 线程创建数量尽量不要超过500个,尽量控制在200个之内;
相关文章
|
3天前
|
Java 数据库
【Java多线程】对线程池的理解并模拟实现线程池
【Java多线程】对线程池的理解并模拟实现线程池
11 1
|
3天前
|
设计模式 消息中间件 安全
【Java多线程】关于多线程的一些案例 —— 单例模式中的饿汉模式和懒汉模式以及阻塞队列
【Java多线程】关于多线程的一些案例 —— 单例模式中的饿汉模式和懒汉模式以及阻塞队列
9 0
|
3天前
|
Java
【Java多线程】分析线程加锁导致的死锁问题以及解决方案
【Java多线程】分析线程加锁导致的死锁问题以及解决方案
11 1
|
3天前
|
存储 缓存 安全
【Java多线程】线程安全问题与解决方案
【Java多线程】线程安全问题与解决方案
10 1
|
3天前
|
Java 调度
【Java多线程】线程中几个常见的属性以及状态
【Java多线程】线程中几个常见的属性以及状态
8 0
|
3天前
|
Java 调度
【Java多线程】对进程与线程的理解
【Java多线程】对进程与线程的理解
11 1
|
3天前
|
安全 C++
C++多线程编程:并发与同步
C++多线程编程:并发与同步
8 0
|
4天前
|
算法 安全 调度
【C++入门到精通】 线程库 | thread类 C++11 [ C++入门 ]
【C++入门到精通】 线程库 | thread类 C++11 [ C++入门 ]
14 1
|
4天前
|
存储 安全 Java
【探索Linux】P.21(多线程 | 线程同步 | 条件变量 | 线程安全)
【探索Linux】P.21(多线程 | 线程同步 | 条件变量 | 线程安全)
10 0
|
4天前
|
算法 安全 Linux
【探索Linux】P.20(多线程 | 线程互斥 | 互斥锁 | 死锁 | 资源饥饿)
【探索Linux】P.20(多线程 | 线程互斥 | 互斥锁 | 死锁 | 资源饥饿)
11 0