多线程笔记一 future和async的使用

1.std::future<int> t1 = async(func1)

线程不能用for循环创建

 2.只有数据大于一定的范围线程才有节约空间的效果,不然线程创建也消耗时间

创建三个函数

 测试消耗时间:当数据为1千万

 

 

  测试消耗时间:当数据为1万

 

// ThreadTry.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
#include <thread>
#include <mutex>
#include <fstream>
#include <deque>
#include <condition_variable>
#include <future>
using namespace std;

int func1()
{
    int data = 0;
    for (int i=0;i<10000;i++)
    {
        data += 1;
    }
    return data;
}

int func2()
{
    int data = 0;
    for (int i = 0; i < 10000; i++)
    {
        data += 1;
    }
    return data;
}

int func3()
{
    int data = 0;
    for (int i = 0; i < 10000; i++)
    {
        data += 1;
    }
    return data;
}

int main()
{
    clock_t start_t, end_t;
    double total_t;

    start_t = clock();

    std::cout << "程序启动,start_t = " << start_t << std::endl;

    int sum = 0;
    
    /*sum = func1() + func2() + func3();*/
    std::future<int> t1 = async(func1);
    std::future<int> t2 = async(func2);
    std::future<int> t3 = async(func3);
    sum += t1.get() + t2.get() + t3.get();

    std::cout << "sum: " << sum << std::endl;

    end_t = clock();

    std::cout << "耗时操作结束,end_t = " << end_t << std::endl;

    total_t = (double)(end_t - start_t) / CLOCKS_PER_SEC;

    std::cout << "CPU 占用的总时间:" << total_t << std::endl;

    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_38409301/article/details/120923690