从我的C ++ 11主循环在自己的线程中读取和写入不同的文件 [英] Reading and writing different files in their own threads from my main loop in C++11

查看:70
本文介绍了从我的C ++ 11主循环在自己的线程中读取和写入不同的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

然后,我试图理解一些代码,这些代码必须从我的应用程序的主循环读取,并写入许多不同的文件中。我希望使用VS 2013中提供的C ++ 11模型。

I am trying to understand, then, write some code that has to read from, and write to many different files and do so from the main loop of my application. I am hoping to use the C++11 model present in VS 2013.

我不想停滞主循环,因此我正在研究每次请求时都会拆分线程。

I don't want to stall the main loop so I am investigating spinning off a thread each time a request to write or read a file is generated.

我尝试了很多事情,包括使用 async 关键字,这听起来很有希望。我将一些代码简化为一个简单的示例:

I've tried many things including using the async keyword which sounds promising. I boiled down some code to a simple example:

#include <future>
#include <iostream>
#include <string>

bool write_file(const std::string filename)
{
    std::cout << "write_file: filename is " << filename << std::endl;

    std::this_thread::sleep_for(std::chrono::milliseconds(2000));

    std::cout << "write_file: written" << std::endl;

    return true;
}

int main(int argc, char* argv[])
{
    const std::string filename = "foo.txt";

    auto write = std::async(std::launch::async, write_file, filename);

    while (true)
    {
        std::cout << "working..." << std::endl;
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
        std::cout << "write result is " << write.get() << std::endl;
    }
}

我正在努力了解基本知识,但我的期望是代码将不断打印正在工作...并在输出中插入的是write_file的开始和结束消息。相反,我看到 write_file 线程似乎阻塞了主循环输出,直到计时器到期。

I'm struggling to understand the basics but my expectation would be that this code would constantly print "working..." and interspersed in the output would be the write_file start and end messages. Instead, I see that the write_file thread seems to block the main loop output until the timer expires.

我意识到我也需要考虑互斥/锁定代码以实际写入文件,但我想首先了解这一点。

I realize I need to also consider mutex/locking on the code to actually write the file but I would like to understand this bit first.

谢谢,如果您能指出正确的方向。

Thank you if you can point me in the right direction.

莫莉。

推荐答案

write.get() 将等待异步任务完成。您要使用 wait_for() 代替:

do {
    std::cout << "working...\n";
} while(write.wait_for(std::chrono::milliseconds(100)) != std::future_status::ready);

std::cout << "write result is " << write.get() << "\n";

这篇关于从我的C ++ 11主循环在自己的线程中读取和写入不同的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆