linux c++ 多线程编程

本文转载自http://www.cnblogs.com/xuxm2007/archive/2011/04/01/2002217.html

如何在linux 下c++中类的成员函数中创建多线程
 
linux系统中线程程序库是POSIX pthread。POSIX pthread它是一个c的库,用C语言进行多线程编程我这里就不多说了,网上的例子很多。但是如何在C++的类中实现多线程编程呢?如果套用C语言中创建多线程的方式,在编译的时候会出现...does not match `void*(*)(void*)..这样的错误。出现这种情况的原因是,编译器在处理C++和C文件上是不同的,也就是说C++和C语言里边指针函数不等价。解决这种错误的方法
 
有两种:
1、不要将线程函数定义为类的成员函数,但是在类的成员函数里边调用它。
例如:
[test.h]
#ifndef TEST_H
#define TEST_H
 
class test
{
public:
    test();
    ~test();
private:
    void createThread();
};
 
#endif
 
[test.cpp]
test::test()
{}
test::~test()
{}
 
void *threadFunction()
{
    printf("This is a thread");
 
    for(;;);
}
 
void test::createThread()
{
    pthread_t threadID;
 
    pthread_create(&threadID, NULL, threadFunction, NULL);
}
 
[main.cpp]
 
#inlcude "test.h"
 
int main()
{
    test t;
    t.createThead();
 
    for(;;);
 
    return 0;
}
 
2、将线程函数作为类的成员函数,那么必须声明改线程函数为静态的函数,并且该线程函数所引用的其他成员函数也必须是静态的,如果要使用类的成员变量,则必须在创建线程的时候通过void *指针进行传递。
例如:
【test.h】
#ifndef TEST_H
#define TEST_H
 
class test
{
public:
    test();
    ~test();
private:
    int p;
    static void *threadFction(void *arg);
    static void sayHello(int r);
    void createThread();
};
 
#endif
 
[test.cpp]
test::test()
{}
test::~test()
{}
 
void *test::threadFunction(void *arg)
{
    int m = *(int *)arg;
    sayHello(m);
 
    for(;;);
}
 
void sayHello(int r)
{
    printf("Hello world %d!\n", r);
}
void test::createThread()
{
    pthread_t threadID;
 
    pthread_create(&threadID, NULL, threadFunction, NULL);
}
 
[main.cpp]
 
#inlcude "test.h"
 
int main()
{
    test t;
    t.createThead();
 
    for(;;);
 
    return 0;
}
 
个人总结:
由于类中的静态函数无法调用类的非静态成员,想要调用非静态成员方法,并非只能使用C调用c++成员方法,在c++静态方法中,对对象进行转换即可实现,静态方法调用非静态方法。代码如下:
【test.h】
#ifndef TEST_H
#define TEST_H
 
class test
{
public:
    test();
    ~test();
private:
    int p;
    static void *threadFction(void *arg);
    void sayHello();
    void createThread();
};
 
#endif
 
[test.cpp]
test::test()
{}
test::~test()
{}
 
void *test::threadFunction(void *arg)
{
            test *f=static_cast<test *>(arg);
            f->sayHello();
            return NULL;
}
 
void sayHello()
{
    printf("Hello world %d!\n", p);
}
void test::createThread()
{
    pthread_t threadID;
 
    pthread_create(&threadID, NULL, threadFunction, this);
}
 
[main.cpp]
 
#inlcude "test.h"
 
int main()
{
    test t;
    t.createThead();
 
    for(;;);
 
    return 0;
}

原文链接: https://www.cnblogs.com/dillyant/archive/2012/09/20/2696158.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    linux c++ 多线程编程

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/63280

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月9日 上午10:51
下一篇 2023年2月9日 上午10:51

相关推荐