#include <Windows.h>
#include <process.h>
#include <stdio.h>
#include <fstream>
#include <iostream>
#include <conio.h>
using namespace std;
ofstream myfile;
unsigned int __stdcall mythreadA(void* data)
{
for (int i = 0; i < 1000000; i++)
{
myfile << "aa";
myfile << i;
myfile << "\n";
}
return 0;
}
int main(int argc, char* argv[])
{
myfile.open ("report.txt");
HANDLE myhandleA, myhandleB,myhandleC;
myhandleA = (HANDLE)_beginthreadex(0, 0, &mythreadA, 0, 0, 0);
myhandleB = (HANDLE)_beginthreadex(0, 0, &mythreadA, 0, 0, 0);
myhandleC = (HANDLE)_beginthreadex(0, 0, &mythreadA, 0, 0, 0);
getchar();
myfile.close();
return 0;
}
如果我们在microsoft visual studio中运行此程序,它会创建一个文件“report”,然后三个线程尝试从1到1000000写入它。但由于并发运行三个线程,数字写入文件不规则。有一些方法,比如mutex和...来解决这个问题,但我只想使用汇编指令“TSL”。我希望这些线程能够相互运行并用“TSL”指令解决这个问题而不是其他方式。