我遇到了这个问题,我有一个主循环,它需要触发异步工作,而不是等待它完成。我想让它做的是检查每一次while循环是否完成了异步工作。这可以使用future.wait_for()来完成。
因为我不想阻塞主循环,所以可以使用future.wait_for(0)。到目前一切尚好。
此外,我想验证我是否在X毫秒内收到(或没有收到)答复。我可以通过检查我启动"async“有多长时间来做到这一点,并验证首先出现的是X毫秒还是返回future_status::ready。
我的问题是,这是一种好的做法,还是有更好的方法呢?
更多信息:由于主循环必须启动许多不同的异步作业,这意味着我需要有很多重复的代码-每次启动都需要“记住”它启动的时间戳,每次我检查异步作业是否准备就绪时,我需要重新计算每个异步作业的时间差。这可能是一个相当麻烦的问题。
现在-这是我描述的一个例子(可能有构建错误):
#define MAX_TIMEOUT_MS 30
bool myFunc()
{
bool result = false;
//do something for quite some time
return result;
}
int main()
{
int timeout_ms = MAX_TIMEOUT_MS;
steady_clock::time_point start;
bool async_return = false;
std::future_status status = std::future_status::ready;
int delta_ms = 0;
while(true) {
// On first time, or once we have an answer, launch async again
if (status == std::future_status::ready) {
std::future<bool> fut = std::async (std::launch::async, myFunc);
start = steady_clock::now(); // record the start timestamp whenever we launch async()
}
// do something...
status = fut.wait_for(std::chrono::seconds(0));
// check how long since we launched async
delta_ms = chrono::duration_cast<chrono::milliseconds>(steady_clock::now() - start).count();
if (status != std::future_status::ready && delta_ms > timeout_ms ) {
break;
} else {
async_return = fut.get();
// and we do something with the result
}
}
return 0;
}发布于 2020-07-17 22:47:03
您可能需要考虑的一件事是:如果您的while循环不做任何相关工作,而只是检查任务完成情况,那么您可能正在执行忙等待(https://en.wikipedia.org/wiki/Busy_waiting)。这意味着你正在浪费大量的CPU时间做无用的工作。这听起来可能有悖于直觉,但它会对您评估任务完成情况的性能产生负面影响,即使您经常检查它!
这可能是因为这个线程看起来像是在对操作系统做大量工作,并且将获得高优先级的处理。这可能会使其他线程(正在执行异步工作)看起来不那么重要,并且需要更长的时间才能完成。当然,这并不是一成不变的,任何事情都可能发生,但如果你不在该循环中做任何其他工作,这仍然是对CPU的浪费。
wait_for(0)不是最好的选择,因为它有效地中断了这个线程的执行,即使工作还没有准备好。它可能需要比您预期的更长的时间才能恢复工作(https://en.cppreference.com/w/cpp/thread/future/wait_for)。future似乎还没有真正的非阻塞应用编程接口(C++ async programming, how to not wait for future?),但是您可以使用其他资源,比如互斥和try_lock (http://www.cplusplus.com/reference/mutex/try_lock/)。
也就是说,如果您的循环仍在做重要的工作,则可以使用此流。但您可能希望检查已完成作业的队列,而不是一个单独的将来。这个队列只会被你的主线程使用,并且可以通过一个非阻塞的线程安全的"try_get“调用来实现,以获得下一个完成的作业。正如其他人评论的那样,您可能希望将节省时间的逻辑包装在作业分派器类或类似类中。
可能是这样的(伪代码!):
struct WorkInfo {
time_type begin_at; // initialized on job dispatch
time_type finished_at;
// more info
};
thread_safe_vector<WorkInfo> finished_work;
void timed_worker_job() {
info.begin_at = current_time();
do_real_job_work();
WorkInfo info;
info.finished_at = current_time();
finished_work.push(some_data);
}
void main() {
...
while (app_loop)
{
dispatch_some_jobs();
WorkInfo workTemp;
while (finished_work.try_get(&work)) // returns true if returned work
{
handle_finished_job(workTemp);
}
}
...
}如果您不熟悉,我还建议您阅读有关线程池(https://en.wikipedia.org/wiki/Thread_pool)和生产者-消费者(https://en.wikipedia.org/wiki/Producer%E2%80%93consumer_problem)的内容。
发布于 2020-07-18 00:10:04
下面的代码异步运行任务,并在稍后检查它们是否完成。
我添加了一些假的工作,并等待看到结果。
#define MAX_TIMEOUT_MS 30
struct fun_t {
size_t _count;
bool finished;
bool result;
fun_t () : _count (9999), finished (false), result (false) {
}
fun_t (size_t c) : _count (c), finished (false), result (false) {
}
fun_t (const fun_t & f) : _count (f._count), finished (f.finished), result (f.result) {
}
fun_t (fun_t && f) : _count (f._count), finished (f.finished), result (f.result) {
}
~fun_t () {
}
const fun_t & operator= (fun_t && f) {
_count = f._count;
finished = f.finished;
result = f.result;
return *this;
}
void run ()
{
for (int i = 0; i < 50; ++i) {
cout << _count << " " << i << endl;;
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
result = true;
finished = true;
cout << " results: " << finished << ", " << result << endl;
}
operator bool () { return result; }
};
int main()
{
int timeout_ms = MAX_TIMEOUT_MS;
chrono::steady_clock::time_point start;
bool async_return = false;
std::future_status status = std::future_status::ready;
int delta_ms = 0;
std::map<size_t, fun_t> futs;
std::vector<std::future<void>> futfuncs;
size_t count = 0;
bool loop = true;
cout << "Begin --------------- " << endl;
while (loop) {
loop = false;
// On first time, or once we have an answer, launch async again
if (count < 3 && status == std::future_status::ready) {
//std::future<bool> fut = std::async (std::launch::async, myFunc);
futs[count] = std::move(fun_t(count));
//futs[futs.size() - 1].fut = std::async (std::launch::async, futs[futs.size() - 1]);
futfuncs.push_back (std::move(std::async(std::launch::async, &fun_t::run, &futs[count])));
}
// do something...
std::this_thread::sleep_for(std::chrono::seconds(2));
for (auto & f : futs) {
if (! f.second.finished) {
cout << " Not finished " << f.second._count << ", " << f.second.finished << endl;
loop = true;
} else {
bool aret = f.second;
cout << "Result: " << f.second._count << ", " << aret << endl;;
}
}
++count;
}
for (auto & f : futs) {
cout << " Verify " << f.second._count << ", " << f.second.finished;
if (f.second.finished) {
bool aret = f.second;
cout << "; result: " << aret;
}
cout << endl;
}
cout << "End --------------- " << endl;
return 0;
}在删除行(有太多行)之后,您会看到任务。第一个数字是任务id,第二个是迭代号。
Begin ---------------
0 0
0 1
0 2
Not finished 0, 0
1 0
0 20
1 1
Not finished 0, 0
Not finished 1, 0
2 0
1 20
0 40
2 1
0 49 // here task 0 ends
2 10
1 30
results: 1, 1 // "run" function ends
1 39
Result: 0, 1 // this is the verification "for"
Not finished 1, 0
Not finished 2, 0
results: 1, 1
Result: 0, 1
Result: 1, 1
Result: 2, 1
Verify 0, 1; result: 1
Verify 1, 1; result: 1
Verify 2, 1; result: 1
End --------------- https://stackoverflow.com/questions/62950334
复制相似问题