C++在成员函数中创建thread多线程, 以成员函数作为回调函数时的范例

以下代码来自VSLAM开源算法ORB_SLAM2中的部分代码,其开源网址为https://github.com/raulmur/ORB_SLAM2

回调函数&成员函数:

void Initializer::FindHomography(vector &vbMatchesInliers, float &score, cv::Mat &H21)
{
    // Number of putative matches
    const int N = mvMatches12.size();

    // Normalize coordinates
    vector vPn1, vPn2;
    cv::Mat T1, T2;
    Normalize(mvKeys1,vPn1, T1);
    Normalize(mvKeys2,vPn2, T2);
    cv::Mat T2inv = T2.inv();

    // Best Results variables
    score = 0.0;
    vbMatchesInliers = vector(N,false);

    // Iteration variables
    vector vPn1i(8);
    vector vPn2i(8);
    cv::Mat H21i, H12i;
    vector vbCurrentInliers(N,false);
    float currentScore;

    // Perform all RANSAC iterations and save the solution with highest score
    for(int it=0; itscore)
        {
            H21 = H21i.clone();
            vbMatchesInliers = vbCurrentInliers;
            score = currentScore;
        }
    }
}

在成员函数:

Initializer::Initializer(const Frame &ReferenceFrame, float sigma, int iterations)

中创建thread线程:

    // Launch threads to compute in parallel a fundamental matrix and a homography
    vector vbMatchesInliersH, vbMatchesInliersF;
    float SH, SF;
    cv::Mat H, F;

    thread threadH(&Initializer::FindHomography,this,ref(vbMatchesInliersH), ref(SH), ref(H));

Tips:

  1. 传递了“this”指针
  2. 传递引用参数要用到“std::ref”来Constructs an object of the appropriate reference_wrapper type to hold a reference to elem

你可能感兴趣的:(C++)