-1

I used a DLIB parallel_for loop to do some processing and add coordinates to a vector> that has been declared outside the loop. But I cannot use the vector.push_back() function from within the loop.

Verified whether there are any declaration issues. Passed the vector pointer to the parallel_for loop lambda function.

    //Store cordinates of respective face_image
    std::vector<pair<int,int>> xy_coords;

    //Create a dlib image window
    window.clear_overlay();
    window.set_image(dlib_frame);

    auto detections = f_detector(dlib_frame);

    dlib::parallel_for(0, detections.size(), [&,detections,xy_coords](long i)
        {
            auto det_face = detections[i];

            //Display Face data to the user
            cout << "Face Found! " << "Area: " << det_face.area() << "X: " <<det_face.left() << "Y: " << det_face.bottom() << endl;

            //Get the Shape details from the face
            auto shape = sp(dlib_frame, det_face);


            //Extract Face Image from frame
            matrix<rgb_pixel> face_img;
            extract_image_chip(dlib_frame, get_face_chip_details(shape, 150, 0.25), face_img);
            faces.push_back(face_img);
            //Add the coordinates to the coordinates vector

            xy_coords.push_back(std::pair<int,int>((int)det_face.left(),(int)det_face.bottom()));

            //Add face to dlib image window
            window.add_overlay(det_face);

        });
  • 1
    No wonder you cannot. This code appears to execute in parallel and vector is simply not thread-safe. You'll need to either add synchronization or provided partition data so that threads don't overwrite each other's data. – Tanveer Badar Jun 17 '19 at 08:50
  • what is the meaning of "does not work" ? Why you cannot use push_back in the loop? Are there compiler errors? runtime errors? unexpected results? – 463035818_is_not_an_ai Jun 17 '19 at 08:51
  • 1
    For thread safety (after fixing any other errors) you can just make `xy_coords` the same size as `detections` and assign to it instead of `push_back` in your loop. – George Jun 17 '19 at 08:57
  • I hate such long lambdas (they are often very confusing). If lambda is longer then 3 lines (literally), I always define a function/method which is invoked from that lambda (which is now one line). – Marek R Jun 17 '19 at 09:09

1 Answers1

1

Your lambda is capturing xy_coords by copy, the one you're pushing into inside the lamdba is not the same outside. Try capturing it by reference like so [&,&xy_coords,detections] or just [&,detections].

See this for more info: https://en.cppreference.com/w/cpp/language/lambda#Lambda_capture

Silvano Cerza
  • 954
  • 5
  • 16