简体   繁体   English

用C ++线程写入文件

[英]Write to file in thread, C++

I wrote a program, which should write "1" in thread for three seconds. 我编写了一个程序,该程序应该在线程中写入“ 1”三秒钟。 But when I try to debug or add controls outputs, I realize that the thread often isn't created (no outputs in the console or achievements of debug point). 但是,当我尝试调试或添加控件输出时,我意识到通常不会创建线程(控制台中没有输出或调试点的实现)。 When I check the return value of CreateThread() , it's ok. 当我检查CreateThread()的返回值时,就可以了。 I read about log in file for I/O, but I think I don't need it. 我读到有关I / O登录文件的信息,但我认为我不需要它。 I want a program with two threads; 我想要一个带有两个线程的程序; one writing "1" for three seconds, and the second writing "2" for three seconds. 一个写“ 1”三秒钟,第二个写“ 2”三秒钟。 Then, compare the result. 然后,比较结果。 Doesn't matter if "1" and "2" are mixed in the input file. 输入文件中是否混合了“ 1”和“ 2”都没有关系。

#include <iostream>
#include <fstream>
#include <windows.h>
#include <stdio.h>
#include <WinBase.h>
#include <ctime>

#define NTHREAD 2

std::ofstream myfile;

DWORD WINAPI fce1 (LPVOID a){
    time_t timerStart, timerNow;
    time(&timerStart);
    timerNow = timerStart;
    while((timerNow - timerStart) < 3)
    {
        myfile << "1";
        myfile.flush();
        time(&timerNow);
    }
    return 0;
}


int main()
{
    HANDLE threads[NTHREAD];
    DWORD dwThreads[NTHREAD];

    myfile.open("file.txt");
    threads[0] = CreateThread(NULL, 0, fce1, NULL, 0, &dwThreads[0]);
    if (threads[0] == NULL){
        printf("Error\n");
    }

    myfile.close();
    return 0;
}

The problem is that your main program closes the file and exits before the thread has finished running, that means that the thread might attempt to write to a closed file and that it will be killed with the process. 问题在于,您的主程序会在线程完成运行之前关闭文件并退出,这意味着线程可能会尝试写入已关闭的文件, 并且该文件将被进程杀死。

You must wait for the thread to finish before exiting the process. 您必须等待线程完成才能退出进程。 You can do this by, for example, using GetExitCodeThread to poll for when the thread has exited. 例如,可以使用GetExitCodeThread轮询线程退出的时间来执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM