mercredi 26 avril 2017

Terminating a thread from a callback function in C++11

I am using an API that communicates with video camera devices. My aim is to take a snapshot with the device.

The API works with callbacks. You connect a callback function to the functionality you want. In this case, taking snapshots.

The functions for doing so look something like this...

MEDIALIB_SETSNAPCB(this, snapcb); // connect snapshot callback to callback function snapcb
MEDIALIB_TAKESNAP(device_nr, channel); // take snapshot of specified channel

The problem is that I need to wait for the callback function snapcb to respond before exiting the program. snapcb may take up to 50 seconds to respond after running MEDIALIB_TAKESNAP, which does not wait for the callback to complete before going to the next line.

Here is a stripped down version:

...
int Snapshot::takeSnap()
{
    MEDIALIB_SETSNAPCB(this, snapcb); // connect snapshot callback to callback function snapcb

    CString device_nr = "TC1234";
    int channel = 1;
    MEDIALIB_TAKESNAP(device_nr, channel); // take snapshot of specified channel
    return 0;
}

void Snapshot::snapcb(const char* device_nr, int channel, const char* pBuf, int nLen, void* pUsr)
{
    Snapshot* pThis = (Snapshot*)pUsr;
    pThis->snapdatacb(device_nr, channel, pBuf, nLen);
}

void Snapshot::snapdatacb(const char* device_nr, int channel, const char* pBuf, int nLen)
{
    // ... create file on computer ...
}
...

I have thought of running MEDIALIB_TAKESNAP(device_nr, channel); in a thread and then firing a conditional variable for when the callback returns, but have been unable to find a example of how to use a conditional variable in this situation.

Any help would be much appreciated. Also, please comment on how I structured my question as I am still learning how to ask a question on stackoverflow.

Aucun commentaire:

Enregistrer un commentaire