linux C++ 类成员函数中创建线程,且能访问类中其他成员变量

最近刚开始玩C++,遇到一些基础问题,下面就是其中之一,将源代码公布一下方便大家查找。

linux C++ 类成员函数中创建线程,且能访问类中其他成员变量.

重点:将线程执行函数声明为非类成员函数,通过参数*arg 将this指针传入线程函数体中。

 

test.h

 

#ifndef TEST_H
#define TEST_H

class test
{
public:
    test();
    ~test();
public:
    int p;
    void sayHello(int r);
    void createThread();
private:
    int q;
};
#endif

 

test.cpp

 

#include "test.h"
#include <string>
#include<pthread.h>
test::test()
{}
test::~test()
{}

void *threadFunction(void *arg)
{
    test *obj = (test *)arg;
    printf("get p:%d",obj->p);
    obj->sayHello(12);
    for(;;);
}

void test::sayHello(int r)
{
    printf("Hello world %d!/n", r);
}
void test::createThread()
{
    p = 1;
    q = 2;
    pthread_t threadID;
    pthread_create(&threadID, NULL, threadFunction, this);
    getchar();
}
~

main.cpp

 

#include "test.h"
#include <string>
#include <iostream.h>
#include <map>

using namespace std;
int main()
{
    test t;
    t.createThread();
    return 0;
}
~

你可能感兴趣的:(linux C++ 类成员函数中创建线程,且能访问类中其他成员变量)