Search code examples
c++intcreatethread

How to pass integer to CreateThread()?


How to pass int parameter to CreateThread callback function? I try it:

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

int id=1;
CreateThread(NULL, NULL, mHandler, (LPVOID)id, NULL, NULL);

But I get warnings:

warning C4311: 'type cast' : pointer truncation from 'LPVOID' to 'int'
warning C4312: 'type cast' : conversion from 'int' to 'LPVOID' of greater size

Solution

  • Pass the address of the integer instead of its value:

    // 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
    }