#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 到它。但是因为三个线程同时运行,所以写入文件的数字是不规则的。有像互斥锁和...这样的方法来解决这个问题,但我只想使用汇编指令“TSL”。我希望这些线程相互运行,并用“TSL”指令解决这个问题,而不是其他方式。