惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V
Visual Studio Blog
Engineering at Meta
Engineering at Meta
月光博客
月光博客
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
T
Tailwind CSS Blog
博客园 - Franky
The GitHub Blog
The GitHub Blog
大猫的无限游戏
大猫的无限游戏
The Cloudflare Blog
B
Blog RSS Feed
云风的 BLOG
云风的 BLOG
小众软件
小众软件
罗磊的独立博客
Microsoft Azure Blog
Microsoft Azure Blog
I
InfoQ
美团技术团队
H
Hackread – Cybersecurity News, Data Breaches, AI and More
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
V
V2EX
C
Check Point Blog
WordPress大学
WordPress大学
博客园 - 【当耐特】
博客园 - 司徒正美
D
Docker

Jia Yue Hua

完美转发不完美 闲散颂 adapting c++20 ranges algorithms for most metaprogramming Reproducible github Developer Environments 使用mpmcpipeline和jthread实现软流水 在当前线程周期回调函数 for_each cpo和tag_invoke transparent,为关联容器增加查找成员
在其它线程周期回调函数
Jia Yue Hua · 2023-05-21 · via Jia Yue Hua

在其它线程周期回调函数

不同于FunctionScheduler ,ThreadedRepeatingFunctionRunner是在另一线程周期回调函数,例子

#include <folly/experimental/ThreadedRepeatingFunctionRunner.h>
#include <iostream>
#include <gtest/gtest.h>
#include <chrono>
#include <thread>
#include <functional>
using namespace folly;
using namespace std;
using std::literals::chrono_literals::operator""s;
using std::literals::chrono_literals::operator""ms;
//running in another thread 
  struct MyClass final {
    MyClass() : count_(0) {}
 
    ~MyClass() {
      threads_.stop();  // Stop threads BEFORE destroying any state they use.
    }
 
    void init() {
      threads_.add("hello", [this]()noexcept {
        return this->incrementCount();
      });
    }
 
    std::chrono::milliseconds incrementCount() noexcept {
      cout<<count_<<endl;
      ++count_;
      return 1000ms;
    }
 
  private:
    std::atomic<int> count_;
    // CAUTION: Declare last since the threads access other members of `this`.
    ThreadedRepeatingFunctionRunner threads_;
  };
TEST(threadedrepeat,runner) { 
  MyClass repeat;
  repeat.init();
  std::this_thread::sleep_for(5s);
}

ThreadedRepeatingFunctionRunner类型的threads_的add函数第一个参数是名字,第二个参数是要周期回调的函数,周期回调的函数返回的参数是duration,单位ms,用于指回调的周期,比如lambda调用的incrementCount返回1000ms,退出前需要调用threads_的stop函数,停止周期回调和退出work线程。

Posted 2023-05-21