pthread.h使用示例

參考:https://blog.csdn.net/chm880910/article/details/48377273

簡單例子:

#include <stdio.h>
#include <pthread.h>
#include <iostream>
using namespace std;


//創建線程示例:
void* thread_1(void* args)
{ 
    
    for( int i = 0;i < 3; i++ )
    printf("This is a pthread.\n");
}

int test_thread_1()
{
    pthread_t id=0;
    int ret;
    
    ret = pthread_create( &id, NULL, thread_1, NULL );
    if ( ret!=0 ) {
        printf ("Create pthread error!\n");
        return 1;
    }
    
    for( int i = 0; i < 3; i++ )
        printf("This is the main process.\n");
        
    pthread_join(id,NULL);
    
    return 0;
}




// 向線程執行函數 傳入參數,以及返回線程執行函數的結果 示例:

void* thread_2( void *arg )
{

    for (int i=0;i<5;i++)
    {
        printf( "This is a thread and arg[%d] = %d.\n",i, ((int*)arg)[i]);
        ((int*)arg)[i] += 1;//plus 1

    }

    return arg;
}

int test_thread_2()
{

    pthread_t th=2;
    int ret;
    int arg[5] = {1,2,3,4,5};

    int *thread_ret = NULL;
    ret = pthread_create( &th, NULL, thread_2, arg );
    if( ret != 0 ){
        printf( "Create thread error!\n");
        return -1;
    }
    printf( "This is the main process.\n" );
    pthread_join( th, (void**)&thread_ret );

    for (int i=0;i<5;i++)
    {
        printf( "thread_ret arg[%d] = %d.\n",i, ((int*)thread_ret)[i]);
    }


    return 0;
}

int main( int argc, char *argv[] )
{

    test_thread_1();
    test_thread_2();
    
    return 0;
}

 

在類中,將類成員函數傳入pthread_create,創建線程,示例:

         需將線程執行函數定義成靜態成員函數

         如需訪問類的非static數據成員, 可將this指針作爲參數傳遞給靜態成員函數,這樣可以通過該this指針訪問非static數據成員;

         如果還需要向靜態函數中傳遞我自己需要的參數,可將this指針和需要的參數作爲一個結構體一起傳給靜態函數;

 具體請看下面示例代碼:

//在類中pthread_create創建線程模板:
class A;
struct ARG
{
     A* pThis;
     string var;
};
class A
{
    public:
        A();
        ~A();
        static void* thread(void* args);
        void  excute();
    private:
        int iCount;

};

A::A()
{
    iCount = 10;
}
A::~A()
{

}
void* A::thread(void* args)
{
     ARG *arg = (ARG*)args;
     A* pThis = arg->pThis;
     string var = arg->var;
     cout<<"傳入進來的參數var: "<<var<<endl;
     cout<<"用static線程函數調用私有變量: "<<pThis->iCount<<endl;

}

void A::excute()
{
     int error;
     pthread_t thread_id;
     ARG *arg = new ARG();
     arg->pThis = this;
     arg->var = "abc";
     error = pthread_create(&thread_id, NULL, thread, (void*)arg);
     if (error == 0)
     {
         cout<<"線程創建成功"<<endl;
         pthread_join(thread_id, NULL);
     }
}


int test_thread_3()
{
    A a;
    a.excute();
    return 0;

}

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章