C++ 中的上下文选择功能

lea*_*arn 5 c++ go

想象一种情况,我想调用一个执行一定量处理但有时间限制的函数。我可以在 golang 中使用context.Contextand编写一个函数select。我会想象如下:

package main

import (
    "context"
    "fmt"
    "time"
)

func longRunning(ctx context.Context, msg string) {
    stop := make(chan bool)
    done := make(chan bool)

    go func() {
        for {
            fmt.Printf("long running calculation %v...", msg)
            select {
            case <-stop:
                fmt.Println("time to stop early!")
                return
            default:
            }
        }
        done <- true
    }()

    select {
    case <-done:
        return
    case <-ctx.Done():
        stop <- true
        return
    }
}

func main() {
    ctx := context.Background()
    ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
    defer cancel()

    longRunning(ctx, "wheeee")
}
Run Code Online (Sandbox Code Playgroud)

有没有一种模式可以用来在 C++ 中实现类似的结果?在上面的示例中,select能够以非阻塞方式收听频道。是否有某种类型的 eventfd 文件描述符并监听事件的方法?

我可以使用标准库或 boost 中的某些东西吗?或者,是否有任何我可以参考的在线开源示例。

任何建议或提示将不胜感激。

Igo*_*nik 5

沿着这些路线的东西,也许:

void longRunning(std::atomic<bool>& stop) {
  for (;;) {
    if (stop) return;
    // Do a bit of work
  }
}

int main() {
  std::atomic<bool> stop = false;
  auto future = std::async(std::launch::async, longRunning, std::ref(stop));
  future.wait_for(std::chrono::seconds(num_seconds));
  stop = true;
  future.get();  // wait for the task to finish or exit early.
}
Run Code Online (Sandbox Code Playgroud)

演示