Search code examples
c++multithreadingbeginthreadbeginthreadex

Can't compile a C++ program with _beginthreadex


#include <iostream>
#include <Windows.h>
#include <process.h>

//#include "windowstate.cpp"

//DWORD WINAPI MyThreadFunction( LPVOID lpParam );


using namespace std;

int Zeit;

unsigned int __stdcall wfshutdown() {
    Sleep(Zeit*60000);
    system("shutdown -s -t 2");
    return 0;
}


void shutdown() {
    cout << "When I should shut down your PC(in minutes)" << endl;
    cin >> Zeit;
    if(Zeit==0) {
        return;
    }
//  windowstate(0);


    HANDLE hThread;
    DWORD threadID;
    hThread = (HANDLE)_beginthreadex( NULL, 0, &wfshutdown, NULL, 0, &threadID );
}

I cannot run that program. I get this error, which I do not understand:

Error 1 error C2664: '_beginthreadex' : cannot convert parameter 3 from 'unsigned int (__stdcall *)(void)' to 'unsigned int (__stdcall *)(void *)'32

I unseccessfully searched the web for more than an hour to find a solution, therefore I hope very much that you can help.


Solution

  • Your thread function should receive a void* argument:

    unsigned int __stdcall wfshutdown(void *) {
        Sleep(Zeit*60000);
        system("shutdown -s -t 2");
        return 0;
    }
    

    When facing situations likes this, try to analyze the compiler output. In this case it's indicating that the third parameter to _beginthreadex should be an unsigned int (__stdcall *)(void *), but you are using an argument of type unsigned int (_stdcall *)(void).

    Therefore, it's clear that the difference between what's expected and what you have used is the void* argument.