linux下 c++多线程的实现
来源:互联网 发布:绘画板 知乎 编辑:程序博客网 时间:2024/05/11 16:05
由于pthread是c库,直接g++编译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++)
- linux下多线程的实现
- Linux下的C多线程编程
- Linux下的C多线程编程
- Linux下的C多线程编程
- Linux下的C语言多线程编程
- Linux下的C语言多线程编程
- Linux下C语言的多线程编程
- linux下c语言的多线程编程
- linux下 c++多线程的实现
- linux下内核多线程的简单实现
- linux 下 c++ 多线程的实现
- Linux 下多线程排序的实现
- linux 下c++多线程的简单实现
- linux下 多线程的实现 C++
- Linux下C语言实现多线程文件复制
- Android 培训计划:如何从功能机时代的 C/C++ 工程师转型至 Android 工程师
- in_addr,char* ,unsigned long 之间的互相转换
- MFC 自绘窗口非客户区
- 数理逻辑:命题逻辑(5)可推出关系
- 《新白发魔女传》之自创歌曲 《绝缘》
- linux下 c++多线程的实现
- 20.输入一个表示整数的字符串,把该字符串转换成整数并输出
- JS闭包的概念
- LearnVSXNow! #14- VSCT文件基础
- 数理逻辑:命题逻辑(6)对偶关系
- 排序之快速排序
- 重复提交
- 改变我的习惯
- iOS项目开发经验:【常用代码3】