linux c++类中的成员函数里创建多线程要注意的地方
来源:互联网 发布:mac系统查询ip地址 编辑:程序博客网 时间:2024/06/13 10:23
如何在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;
}
- 在linux c++类中的成员函数里创建多线程要注意的地方
- linux c++类中的成员函数里创建多线程要注意的地方
- 在linux c++类中的成员函数里创建多线程要注意的地方
- c语言函数一个要注意的地方
- 关于linux中的CONNTRACK_MAX和HASHSIZE要注意的地方
- 关于linux中的CONNTRACK_MAX和HASHSIZE要注意的地方
- linux多线程创建时使用类成员函数作为参数
- linux多线程创建时使用类成员函数作为参数
- linux多线程创建时使用类成员函数作为参数
- 如何在linux 下c++中类的成员函数中创建多线程
- 如何在linux 下c++中类的成员函数中创建多线程
- 多线程,成员函数内创建线程,线程函数调用类内的其他成员函数
- 创建多线程API调用类成员函数的方式
- 编写可重入函数要注意的地方
- isnumberic函数要注意的地方
- main函数参数要注意的地方
- Linux内核实验要注意的地方
- C语言(5) 函数使用需要注意的地方
- java i/o 详解
- ffmpeg提取es命令
- windows程序设计之计时器(一)
- 在链表中删除指定值的元素
- Maven设置HTTP代理
- linux c++类中的成员函数里创建多线程要注意的地方
- 最火Android模拟神器Genymotion之安装过程详解
- linux 输入输出 重定向 语法
- 项目所需的应用程序未安装,确保已安装项目类型(.csproj)的应用程序的解决办法
- LINUX ulimit命令
- VS2010出现FileTracker : error FTK1011编译错误的解决办法
- SqlServer数据库备份、还原
- UNIX之fork进程copy
- Java 学习笔记三