簡體   English   中英

避免使用多線程C ++優化的變量

[英]Avoid a variable optimized out with multithread c++

我正在用C ++編寫程序,並且有一個使用.detach();的線程; 當我嘗試從中訪問另一個線程時,調試器說響應已被優化,我無法訪問它。 有什么辦法可以“解決”該問題嗎? 謝謝

這里有代碼:

int foos;
unsigned int ReadProcess(HANDLE phandle, unsigned int address) {
    unsigned int Pointer;
    ReadProcessMemory(phandle, (void*)(address), &Pointer, sizeof(address), 0);
    return Pointer;
}

void foo()
{
    while (1) {
        if (foos == 1) { break; }
        volatile unsigned int xPointer, xBaseaddress = 0x002CF7DC, xoffset = 0x448, xoffset1 = 0x198, xoffset2 = 0x498, xoffset3 = 0x268, xoffset4 = 0x24;
        HANDLE phandle = GetProcessHandle("Speed Calculator");
        DWORD Base = (DWORD)GetBaseAddress(phandle);
        xPointer = Base + xBaseaddress; //xPointer optimized out here
        xPointer = ReadProcess(phandle, xPointer) + xoffset; //and here
        xPointer = ReadProcess(phandle, xPointer) + xoffset1; //and here
        xPointer = ReadProcess(phandle, xPointer) + xoffset2; //and here
        xPointer = ReadProcess(phandle, xPointer) + xoffset3; //and here
        xPointer = ReadProcess(phandle, xPointer) + xoffset4; //and here
        if (!SendMessage(textBox1, WM_SETTEXT, NULL, (LPARAM)("IS: ") + xPointer))//and because of that, here
            MessageBox(0, "Error: " + GetLastError(), "Error", MB_OK);
        Sleep(299);
    }
}

void main() {

                foos = 0;
                std::thread first(foo);
                first.detach();

}

我已經忽略了部分代碼,因為它主要是win32 api交互。

已使用要求優化代碼的參數調用了編譯器。

Visual Studio示例

查看您在Visual Studio中的解決方案配置(在下拉列表中可以選擇ReleaseDebug )。

如果更改為“ Debug則不應優化變量,您可以看到正在發生的情況。

更改解決方案配置時,將發生的情況是Visual Studio在調用編譯器時為其設置參數。 在這種情況下,我們希望/Od (Disabled)標志用於Configuration properties→C/C++→Optimization→Optimization ,而不是/O2 (Maximize Speed)

在調試過程中,您還可以打開“線程”窗口以查看創建的線程。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM