Search code examples
c++opencvosx-snow-leopardboost-thread

Problem accessing camera when using Boost thread on OSX


I'm trying to use OpenCV to open a camera. This works fine when I open the camera in the main thread, but when I try to open the camera while in a Boost thread, it fails. I haven't been able to google why this happens. I assume it's somehow related to the permissions of the Boost thread.

The following works fine:

#include <cv.h>
#include <boost/thread.hpp>
#include <highgui.h>

using namespace cv;
void openCamera() {
    Ptr< VideoCapture > capPtr(new VideoCapture(0)); // open the default camera
}

int main() {
    openCamera();
}

And my camera turns on briefly after which I get the message "Cleaned up camera" as one would expect.

But when I try the same through a Boost thread, it doesn't open the camera:

#include <cv.h>
#include <boost/thread.hpp>
#include <highgui.h>
#include <iostream>

using namespace cv;
void openCamera() {
    std::cout << "confirming that openCamera() was called" << std::endl;
    Ptr< VideoCapture > capPtr(new VideoCapture(0)); // open the default camera
}

int main() {
    boost::thread trackerThread( boost::bind(openCamera) );
}

This prints "confirming that openCamera() was called", but the camera never turns on and there is no "Cleaned up camera" message.

Is there any way I can fix it?

Thanks!


Solution

  • I don't use boost a lot, but don't you need to do something to keep main() from exiting while your thread works? Like maybe...

    int main() {
        boost::thread trackerThread( boost::bind(openCamera) );
        trackerThread.join();
    }