run function in separate thread in winapi c++ application

208 views Asked by At

I need to run this fuction in separate thread:

EdsError downloadEvfData(EdsCameraRef camera)
{
    EdsError err = EDS_ERR_OK;
    // some code skipped
}

I call this function like this:

HANDLE thread = CreateThread(NULL,0,downloadEvfData,camera,0,NULL);

But get this error:

invalid conversion from 'void (*)(EdsCameraRef)' {aka 'void (*)(__EdsObject*)'} to 'LPTHREAD_START_ROUTINE' {aka 'long unsigned int (__attribute__((stdcall)) *)(void*)'} 

How can I fix it? Thanks a lot!

2

There are 2 answers

7
Simon Mourier On

Your downloadEvfData function doesn't have the expected LPTHREAD_START_ROUTINE signature, you can do something like this instead (if EdsCameraRef is a pointer) :

EdsError downloadEvfData(EdsCameraRef camera)
{
    EdsError err = EDS_ERR_OK;
    // some code skipped
}

DWORD ThreadProc(PVOID camera)
{
    downloadEvfData((EdsCameraRef)camera);
    return 0; // thread exit return
}


HANDLE thread = CreateThread(NULL, 0, ThreadProc, camera, 0, NULL);
0
cjl On

EDSDK's example do as this to create a thread

static EdsError downloadEvfData(void* param)
{
    EdsError err = EDS_ERR_OK;
    EdsCameraRef camera = (EdsCameraRef)param;
    // some code skipped
}

HANDLE _hThread = (HANDLE)_beginthread(dowloadEvfData, 0, camera);

you can use c++11 to create a thread as this

std::unique_ptr<std::thread> pthd(nullptr);
pthd.reset(new std::thread([&]){
   downloadEvfData(camera);
})
pthd->join();

One important note

//When using the SDK from another thread in Windows, 
// you must initialize the COM library by calling CoInitialize 
CoInitializeEx(NULL, COINIT_MULTITHREADED);
//....
CoUninitialize();