c/c++: 多线程编程基础讲解(二)

在基础一上思考,如果线程调用的函数是在一个类中怎么办?答案是将该函数写成静态成员函数,如下模式就很符合C++的写作模式:

#include <iostream>
#include <pthread.h>

using namespace std;

#define NUM_THREADS 5

class Hello
{
    public:

    static void* say_hello(void* args)//除了多了static关键字,别无异样;
    {
        cout << "hello..." << endl;
    }
};

int main()
{
    pthread_t tids[NUM_THREADS];
    for(int i = 0; i < NUM_THREADS; ++i)
    {
        int ret = pthread_create(&tids[i], NULL, Hello::say_hello, NULL);
        if (ret != 0)
        {
           cout << "pthread_create error: error_code=" << ret << endl;
        }
    }

    pthread_exit(NULL);
}


 

 

 

你可能感兴趣的:(多线程,编程,c,null,Class)