我写了一个程序,它应该在线程中写入"1"三秒钟.但是当我尝试调试或添加控件输出时,我意识到通常不会创建线程(控制台中没有输出或调试点的成就).当我检查的返回值CreateThread(),它的确定.我读了关于I/O的登录文件,但我想我不需要它.我想要一个有两个线程的程序; 一个写"1"三秒钟,第二个写"2"三秒钟.然后,比较的结果.如果"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;
}
Run Code Online (Sandbox Code Playgroud)