c++多線程參數的傳遞


#include <iostream>
#include <pthread.h>        //多線程相關操作頭文件,可移植眾多平台
using namespace std;

struct mypara
{      
    int para1;            //參數1       
    char *para2;        //參數2
    pthread_t wait;
};

void* thread1( void* args )  //本函數演示的是數據的傳出
{
    mypara *my = (mypara *)args;
    srand(unsigned(time(0)));
    my->para1 = rand()%100;
    my->para2 = "";
    cout << "給結構體賦值結束"<< endl;
    return 0;
} 
void* thread2( void* args ) //本函數演示的是數據的傳入
{
    mypara *str_in = (mypara *)args;
    cout << "線程2開始運行........................" <<endl;
    pthread_join(str_in->wait,NULL);    //需要等待thread1線程給struct 結構體賦值結束后才能運行
    cout << "線程1產生的隨機數是:" << str_in->para1<< " "<< str_in->para2 <<endl;
    return 0;
} 
int main()
{
    pthread_t tid1,tid2; 
    mypara my_para;

    int ret = pthread_create( &tid1, NULL, thread1, (void *)&my_para );    
    //pthread_join(tid1,NULL);
    my_para.wait = tid1;
    pthread_create( &tid2, NULL, thread2, (void *)&my_para );
    system("pause");
    pthread_exit( NULL ); 
}

c++多線程參數的傳遞——通過結構體傳遞參數。(pthread多線程類庫,不能在x64位上編譯,【C++ 11 自帶多線程】)


免責聲明!

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



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