我对 std::ifstream
的用法进行了一些谷歌搜索。在一个线程中作为函数参数,但设法在 pthread 中找到它的 C 实现。我想要的是在 C++11 中实现它,因为我使用的是标准 C++ 线程。
我正在尝试传递 std::ifstream
作为线程的参数,但出现以下错误:
error: no type named
type
inclass 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/