如何将整数传递给CreateThread()?

BAr*_*ell 7 c++ int createthread

如何将int参数传递给CreateThread回调函数?我试试看:

DWORD WINAPI mHandler(LPVOID sId) {
...
arr[(int)sId]
...
}

int id=1;
CreateThread(NULL, NULL, mHandler, (LPVOID)id, NULL, NULL);
Run Code Online (Sandbox Code Playgroud)

但我收到警告:

warning C4311: 'type cast' : pointer truncation from 'LPVOID' to 'int'
warning C4312: 'type cast' : conversion from 'int' to 'LPVOID' of greater size
Run Code Online (Sandbox Code Playgroud)

Jon*_*Jon 6

传递整数的地址而不是其值:

// parameter on the heap to avoid possible threading bugs
int* id = new int(1);
CreateThread(NULL, NULL, mHandler, id, NULL, NULL);


DWORD WINAPI mHandler(LPVOID sId) {
    // make a copy of the parameter for convenience
    int id = *static_cast<int*>(sId);
    delete sId;

    // now do something with id
}
Run Code Online (Sandbox Code Playgroud)

  • 它仍然不安全.如果新的线程没有被调度,直到ID超出范围(可能就在`CreateThread`调用之后? (2认同)