c++ - 如何将 ifstream 作为参数传递给 std::thread 函数?

标签 c++ multithreading c++11

我对 std::ifstream 的用法进行了一些谷歌搜索。在一个线程中作为函数参数,但设法在 pthread 中找到它的 C 实现。我想要的是在 C++11 中实现它,因为我使用的是标准 C++ 线程。

我正在尝试传递 std::ifstream作为线程的参数,但出现以下错误:

error: no type named type in class std::result_of<void (*(std::basic_ifstream<char>))(std::basic_ifstream<char>)>
typedef typename result_of<_Callable(_Args...)>::type result_type;

我如何通过 ifstream在线程上调用的函数的参数? 这是我的代码:

#include <cstdlib>
#include <fstream>
#include <thread>
#include <iostream>
using namespace std;

void file_func_1(std::ifstream m_file)
{
    // ifstream m_file;
    string line;
    while (getline(m_file, line)) {
        cout << "the line now in is" << line
             << "from thread" << std::this_thread::get_id()
             << endl;
        std::this_thread::sleep_for(std::chrono::seconds((rand() % 10) + 1));
    }
}

void file_func_2(ifstream m_file)
{
    string line;
    while (getline(m_file, line)) {
        cout << "the line now in is" << line
             << "from thread" << std::this_thread::get_id()
             << endl;
        std::this_thread::sleep_for(std::chrono::seconds((rand() % 10) + 1));
    }
}

int main(int argc, char** argv)
{
    std::ifstream m_file;
    m_file.open("File_line.txt", ios::in);
    int name=8;
    std::thread func_th1(file_func_1, (m_file));
    // thread func_th2(file_func_2,m_file);
    func_th1.join();
    // func_th2.join();
    return 0;
}

最佳答案

这里有两个问题。首先是您不能按值传递流,您需要按引用传递它们。

其次,您似乎无法直接通过线程传递流(尽管可能有变通方法 [编辑:std::ref 似乎有效,尽管有评论 - 也许是版本问题,因为我将 g++ 与 c++1z] 一起使用。

因此,让您的函数访问引用,并在创建线程时使用 lambda 调用您的函数:

#include <cstdlib>
#include <fstream>
#include <thread>
#include <iostream>
#include <functional>

using namespace std;

void file_func_1(std::ifstream &m_file){
    string line;
    while ( getline (m_file,line) ){
        cout<<"the line now in is"<<line<<"from thread"<<std::this_thread::get_id()<<endl;
        std::this_thread::sleep_for(std::chrono::seconds((rand() % 10) + 1));
    }
}

int main(int argc, char** argv) {
    std::ifstream m_file;
    m_file.open("File_line.txt",ios::in);
    int name=8;
    std::thread func_th1([&m_file]() { file_func_1(m_file); });
    std::thread func_th2(file_func_1, ref(m_file));
    func_th1.join();
    func_th2.join();
    return 0;
}

并且不要忘记一次只能有一个线程访问该流,因此将访问包装在某种互斥体中。

关于c++ - 如何将 ifstream 作为参数传递给 std::thread 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40978527/

相关文章:

c++ - 使用基于概念的递归函数模板在扣除 'auto [...] ' 之前使用 'auto'

c++ - 如何在 C 或 C++ 中打印宏名称

C++ Makefile编译顺序

c++ - 在类的析构函数中关闭类的线程成员是个好主意吗?

c++ - 转换 yuv 4 :2:0 file to Rgb not getting expected output

c++ - 析构函数之前工作。如何?

java - java中的CountDownLatch有什么意义?

java - 拥有一个线程池比多个线程池更好的设计

c++ - 类 TESTDLL_LIBSHARED_EXPORT TestDLL_lib

c++ - 解决 std::showbase 不加前缀零的问题