我试图理解为什么当我尝试在写入文件时使用线程。它会在一段时间后停止写入此文件。我理解线程但不太深入。 以下是我使用的示例代码:
#include <chrono>
#include <iostream>
#include <stdlib.h>
# include <stdio.h>
#include <thread>
#include <unistd.h>
// http://www.bogotobogo.com/cplusplus/cpptut.php
using namespace std;
float counter = 0;
void *call_from_thread(void *) {
FILE *f = fopen64("results_text.txt", "a");
if (f == NULL)
{
printf("Error opening file!\n");
exit(1);
}
fprintf(f, " this is some text to be written in the file to see the max size of writting using threads \n");
fclose(f);
printf("|I am in the thread \n" );
usleep(50);
return NULL;
}
int main() {
while (true) {
std::thread t([] {call_from_thread(NULL);});
counter++;
// To let the main thread continue running and detach from the last created thread, the thread must have finished execution before recalling it once again.
// if the thread sleeps more than the main thread, then after some time the program will run out of resources and the program crash
// to test this case: try to put 5000 in the usleep inside the thread
t.detach();
// Will make the main thread wait for the thread till it finishes
//t.join();
printf("|I am alive %f \n", counter);
usleep(100);
}
return 0;
}
我正在使用“detach”功能来保存我计算机上的资源,但在运行一段时间后仍然出现以下错误:
terminate called after throwing an instance of 'std::system_error'
what(): Resource temporarily unavailable
非常感谢任何帮助。