Hi, again, I am trying to run a void function and pass parameters to it on a thread using std::thread. However, I keep getting compile errors. When I can get it to compile it does not create the file. Thanks in advanced. Here is my code:
Line 23 is the culprit. void filehandler(char* amount) doesn't return anything,
thus you cannot write std::thread thread1(filehandler(argv[1]));
Either pass a reference or a pointer (which you're already doing), or change the function's return type.
It's surprising that you would get it to compile at all, what is it that you did to make it work?
I changed the type to int and I also tried std::thread thread1(filehandler, (argv[1])) both compiled but neither actually passed the argument to filehandler().
1) thread function should be void. (you can have return type but it will be ignored)
2) Correct syntax is std::thread thread1(filehandler, argv[1])
3) You have serious logic problems in your conditions. remove them and look if this would work (it should)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
#include <thread>
#include <fstream>
void filehandler(char* amount)
{
std::fstream output("data.txt");)
for(int i = 0; i <= atoi(amount); ++i) {
output << (i) << ("\n");
}
std::cout << "Done!" << std::endl;
}
int main(int argc, char* argv[])
{
std::cout << ("Writing data to file...");
std::thread thread1(filehandler, argv[1]);
thread1.join();
}
TL;DR problem was not in thread, but in messy logic
It tried the test program it did output the contents of argv[0] but mine still does not even say anything when given the wrong arguments. Here is the revised code:
Ok, it now works for the most part. It compiles and passes the arguments to filehandler() which successfully writes it to the file. However, if it is not given any arguments it will segfault.