Home > OS >  How can you pass an ifstream to thread?
How can you pass an ifstream to thread?

Time:04-19

I'm trying to implement multi-threading in my program. I'm trying to make my directory searcher run in a thread, and join for the rest of the function.

The file thread function searches my directory and finds each file, and I'm trying to use this in my file reader section within my main() function.

How should I pass an ifstream path to a thread? After a lot of googling, I'm not any closer to finding an answer due to it being so specific.

void file_thread(std::ifstream& file){
    //open csv file for reading
    std::string path = "path/to/csv";
    for (const auto & f : std::filesystem::directory_iterator(path)){
        std::ifstream file(f.path());
    }
}

int main(){
    std::ifstream file;
        
    std::thread test(file_thread, file);
        
    //if csv is successfully open
    if(file.is_open()) 
    {
        ...
    }
    ...
}

CodePudding user response:

I suspect you actually want this, although its not at all clear why you are using a separate thread

void file_thread(std::ifstream& file){
    //open csv file for reading
    std::string path = "path/to/csv";
    file.open(path);
}

If thats the path, why iterate over the directory

This code still wont help if you call it in a separate thread as main will not wait. Why not just call normally?

std::thread test(file_thread, file);
// the line below will run before file_thread finishes
// thats the whole point of threads

if(file.is_open()) 
{
    ...
}

just do

file_thread(file);
    
//if csv is successfully open
if(file.is_open()) 
{
    ...
}
  • Related