C ++ Win32线程

时间:2018-10-16 00:51:25

标签: c++ multithreading winapi beginthreadex

我在使用_beginthreadex时遇到了一些问题。如何将我创建的函数发送到线程?我对线程完全陌生,这是一个很愚蠢的问题,但是我无法解决

//Function that I want to send to a thread

vector<int>F1(vector<int> A, vector<int> B, vector<int> C, vector<int> D, vector<vector<int>> MA, vector<vector<int>> MD) { 
    vector<int> ResVect;
    ResVect = plusVector(plusVector(A, plusVector(B, C)), VectMultMatr(D, MultMatr(MA, MD)));   
    return ResVect; 
}

//Thread funcF1

int main(){
    HANDLE funcF1, funcF2, funcF3;
    //////F1//////
    cout << "Task 1 starts" << endl;
    vector<int>A = createVect(1, 4);
    vector<int>B = createVect(1, 4);
    vector<int>C = createVect(1, 4);
    vector<int>D = createVect(1, 4);

    vector<vector<int>>MA = createMatrix(1, 4);
    vector<vector<int>>MD = createMatrix(1, 4);

    //vector<int>E = F1(A, B, C, D, MA, MD);
    funcF1 = (HANDLE)_beginthreadex(0, 0, &F1(A, B, C, D, MA, MD), 0, 0, 0);
}

1 个答案:

答案 0 :(得分:4)

如果您阅读_beginthreadex文档,则会发现传递的函数与_beginthreadex期望的签名不匹配:

unsigned ( __stdcall *start_address )( void * )

要做您想做的事情,您需要一个具有确切签名的函数来包装您的真实函数。

请尝试以下类似操作:

vector<int> F1(vector<int> A, vector<int> B, vector<int> C, vector<int> D, vector<vector<int>> MA, vector<vector<int>> MD) {    
    return plusVector(plusVector(A, plusVector(B, C)), VectMultMatr(D, MultMatr(MA, MD)));  
}

struct myVecs {
    vector<int> A;
    vector<int> B;
    vector<int> C;
    vector<int> D;
    vector<vector<int>> MA;
    vector<vector<int>> MD;
};

unsigned __stdcall myThreadFunc(void *arg) {
    myVecs *vecs = (myVecs*) arg;
    vector<int> E = F1(vecs->A, vecs->B, vecs->C, vecs->D, vecs->MA, vecs->MD);
    // use E as needed...
    delete vecs;
    return 0;
}

int main(){
    HANDLE funcF1;

    //////F1//////
    cout << "Task 1 starts" << endl;

    myVecs *vecs = new myVecs;
    vecs->A = createVect(1, 4);
    vecs->B = createVect(1, 4);
    vecs->C = createVect(1, 4);
    vecs->D = createVect(1, 4);
    vecs->MA = createMatrix(1, 4);
    vecs->MD = createMatrix(1, 4);

    funcF1 = (HANDLE) _beginthreadex(0, 0, &myThreadFunc, vecs, 0, 0);
    if (func1 == 0) {
        // error handling...
        delete vecs;
    }

    // do other things as needed...

    // wait for thread to terminate before exiting the app...
    return 0;
}