並發編程: c++11 thread(Func, Args...)利用類成員函數創建線程


c++11是VS2012后支持的新標准,為並發編程提供了方便的std::thread。

使用示例:

#include <thread>

void thread_func(int arg1, int arg2, float* arg3){
    arg3 = (arg1*1.0)/(arg1 + arg2);
    cout << "arg1 / (arg1 + arg2) = " << arg3 << endl;
    return;
}

void main(){
    //線程數
    int threadNum = 3

    //動態分配
    thread* t;
    t = new thread[threadNum];

    //結果
    float *result =  (float *)malloc(threadNum*sizeof(float));
    
    for ( int i = 0; i < threadNum; i++){
        t[i] = thread(thread_func, i, i, &result[i]);    
    }

    for ( int i = 0; i < threadNum; i++){
        //t[i].detach(); //主進程不等子進程運行完
        t[i].join();        //主進程等
    }

    //post-processing towards result...
}

當需要利用類成員函數( MyClass::thread_func )來創建子線程時,需如下碼碼:

t[i] = thread(std::mem_fn(&MyClass::thread_func), Object, args..);    

如果thread_func為static,則不用寫object。否則需要,如主進程所調函數也為該類成員,則傳入this指回自己。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM