0
#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”指令解决这个问题,而不是其他方式。

4

1 回答 1

0

在多线程环境中,最好使用互锁的,并且避免主要为 x64 代码添加 .asm 文件。

于 2014-03-15T12:20:29.800 回答