C++ async 多线程任务异步,封装类似线程池

本文通过一个C++示例展示了如何使用std::async进行异步任务调度。代码创建了一个go类,用于管理std::future,允许并发执行多个任务。每个任务在main函数中被提交,并打印当前时间戳,展示异步执行的顺序与主线程的执行顺序不同,体现了并发执行的特点。
摘要由CSDN通过智能技术生成
#include <map>
#include <iostream>
#include <string>
#include <cstring>
#include <ctime>
#include <functional>
#include <future>
#include <iostream>

#include <chrono>
#define sleep(for_seconds)   std::this_thread::sleep_for(std::chrono::seconds(for_seconds))
#define msleep(for_milliseconds)        std::this_thread::sleep_for(std::chrono::milliseconds(for_milliseconds))

class timeKit
{
public:
   static std::string getTimeStamp(time_t epochTime, const char* format = "[%Y-%m-%d %H:%M:%S] ")
   {
      char timestamp[64] = {0};
      strftime(timestamp, sizeof(timestamp), format, localtime(&epochTime));
      return timestamp;
   }

   static std::string YMD(){
      const time_t curTime = time(0);
      return getTimeStamp(curTime);
  }

   static time_t convertTimeToEpoch(const char* theTime, const char* format = "%Y-%m-%d %H:%M:%S")
   {
      std::tm tmTime;
      memset(&tmTime, 0, sizeof(tmTime));
      strptime(theTime, format, &tmTime);
      return mktime(&tmTime);
   }
};


class go{
public:
        /**
        * sign  : dujingning
        * usage :
        * 1   go Go();
        * 2   Go.work() = std::async(std::launch::async, [](){
        *                       std::cout << hello << std::endl;
        *               });
        */
        go(int number = 20):MAX_FUTURES(number){}
        ~go(){}

        inline int& getFutureIndex () {
                if (++futureIndex >= MAX_FUTURES || futureIndex < 0) {
                        futureIndex = 0;
                }
                return futureIndex;
        }

        std::future<void>& work(int index = -1){
                if ( index < 0 || index >= MAX_FUTURES ) {
                   return futureMap[getFutureIndex()];
                }
                return futureMap[index];
        }

        void work( std::function<void(void)> &f, int index = -1 ){
                if ( index < 0 || index >= MAX_FUTURES ) {
                   futureMap[getFutureIndex()] = std::async(std::launch::async, f);
                   return;
                }
                futureMap[index] = std::async(std::launch::async, f);
        }


        inline int max_futures() { return MAX_FUTURES; }
private:
        int                                     MAX_FUTURES;
        int                                     futureIndex =   -1;
        std::map<int, std::future<void> >       futureMap;
};

void print(std::string info) {
        std::cout << timeKit::YMD() + info << std::endl;
}

/* compile : g++ -std=c++11 go.cpp -pthread -o async */
int main(){
    int i = 20;
    go Go(30);

    while( i-- >0 ) {

        std::string id = std::to_string(i) + "  ";

        print(id + "main before .................................................");

        Go.work() =  std::async(std::launch::async, [id]() {
                    print(id + "async into...");
                    sleep(2);
                    print(id + "async out...");
                  });

        print(id + "main after ...................................................\r\n");

    }

    print("test done~");

    std::function<void(void)> f = [](){
                print("hello world");
        };
    Go.work(f);

}

编译:

g++ -std=c++11 go.cpp -pthread -o async

结果:

[root@jn cpp]# time ./async
[2022-07-29 18:25:52] 19  main before .................................................
[2022-07-29 18:25:52] 19  main after ...................................................

[2022-07-29 18:25:52] 18  main before .................................................
[2022-07-29 18:25:52] 18  main after ...................................................

[2022-07-29 18:25:52] 17  main before .................................................
[2022-07-29 18:25:52] 17  main after ...................................................

[2022-07-29 18:25:52] 16  main before .................................................
[2022-07-29 18:25:52] 16  main after ...................................................

[2022-07-29 18:25:52] 15  main before .................................................
[2022-07-29 18:25:52] 15  main after ...................................................

[2022-07-29 18:25:52] 14  main before .................................................
[2022-07-29 18:25:52] 14  main after ...................................................

[2022-07-29 18:25:52] 13  main before .................................................
[2022-07-29 18:25:52] 13  main after ...................................................

[2022-07-29 18:25:52] 12  main before .................................................
[2022-07-29 18:25:52] 12  main after ...................................................

[2022-07-29 18:25:52] 11  main before .................................................
[2022-07-29 18:25:52] 11  main after ...................................................

[2022-07-29 18:25:52] 10  main before .................................................
[2022-07-29 18:25:52] 10  main after ...................................................

[2022-07-29 18:25:52] 9  main before .................................................
[2022-07-29 18:25:52] 9  main after ...................................................

[2022-07-29 18:25:52] 8  main before .................................................
[2022-07-29 18:25:52] 8  main after ...................................................

[2022-07-29 18:25:52] 7  main before .................................................
[2022-07-29 18:25:52] 7  main after ...................................................

[2022-07-29 18:25:52] 6  main before .................................................
[2022-07-29 18:25:52] 6  main after ...................................................

[2022-07-29 18:25:52] 5  main before .................................................
[2022-07-29 18:25:52] 5  main after ...................................................

[2022-07-29 18:25:52] 4  main before .................................................
[2022-07-29 18:25:52] 4  main after ...................................................

[2022-07-29 18:25:52] 3  main before .................................................
[2022-07-29 18:25:52] 3  main after ...................................................

[2022-07-29 18:25:52] 2  main before .................................................
[2022-07-29 18:25:52] 2  main after ...................................................

[2022-07-29 18:25:52] 1  main before .................................................
[2022-07-29 18:25:52] 1  main after ...................................................

[2022-07-29 18:25:52] 0  main before .................................................
[2022-07-29 18:25:52] 0  main after ...................................................

[2022-07-29 18:25:52] test done~
[2022-07-29 18:25:52] 9  async into...
[2022-07-29 18:25:52] 7  async into...
[2022-07-29 18:25:52] 6  async into...
[2022-07-29 18:25:52] 4  async into...
[2022-07-29 18:25:52] 1  async into...
[2022-07-29 18:25:52] 8  async into...
[2022-07-29 18:25:52] 12  async into...
[2022-07-29 18:25:52] hello world
[2022-07-29 18:25:52] 17  async into...
[2022-07-29 18:25:52] 16  async into...
[2022-07-29 18:25:52] 19  async into...
[2022-07-29 18:25:52] 15  async into...
[2022-07-29 18:25:52] 14  async into...
[2022-07-29 18:25:52] 13  async into...
[2022-07-29 18:25:52] 10  async into...
[2022-07-29 18:25:52] 5  async into...
[2022-07-29 18:25:52] 3  async into...
[2022-07-29 18:25:52] 0  async into...
[2022-07-29 18:25:52] 18  async into...
[2022-07-29 18:25:52] 11  async into...
[2022-07-29 18:25:52] 2  async into...
[2022-07-29 18:25:54] 9  async out...
[2022-07-29 18:25:54] 7  async out...
[2022-07-29 18:25:54] 6  async out...
[2022-07-29 18:25:54] 4  async out...
[2022-07-29 18:25:54] 1  async out...
[2022-07-29 18:25:54] 8  async out...
[2022-07-29 18:25:54] 12  async out...
[2022-07-29 18:25:54] 17  async out...
[2022-07-29 18:25:54] 16  async out...
[2022-07-29 18:25:54] 19  async out...
[2022-07-29 18:25:54] 15  async out...
[2022-07-29 18:25:54] 14  async out...
[2022-07-29 18:25:54] 13  async out...
[2022-07-29 18:25:54] 10  async out...
[2022-07-29 18:25:54] 5  async out...
[2022-07-29 18:25:54] 3  async out...
[2022-07-29 18:25:54] 0  async out...
[2022-07-29 18:25:54] 18  async out...
[2022-07-29 18:25:54] 11  async out...
[2022-07-29 18:25:54] 2  async out...

real    0m2.007s
user    0m0.002s
sys     0m0.004s
[root@jn cpp]#
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值