您的位置:首页 > 编程语言 > C语言/C++

关于C++中posix pthread线程函数在类中封装的问题

2009-08-12 16:00 316 查看
我们通常有这样的需求:需要在C++中用多线程处理可以并行处理的问题,且把线程函数封装在类中,而把线程函数封装在类中,导致了this指针作为默认的参数被传进了函数中,从而和线程函数参数不能匹配,不能通过编译。

市面上一般有以下几种解决方案:

1. 将线程函数作为全局函数, 从而避免了this指针作为隐含参数的作怪行为,但这样线程函数却无法访问类中的私有变量,此为一大缺憾。

解决方案: 是把所有的私有变量变为全局变量,这样极大程度上破坏了类的封装性。

2. 引入友元函数,从而可以访问私有变量,这种方法我没有试过,试过了再补充上来。

3. 将线程函数作为静态函数,因为在C++中静态函数没有this指针(即在内存中静态函数和普通全局函数几乎没有什么区别),故可以匹配编译通过, 但是当线程函数要访问私有变量呢?可以访问到吗?答案是不可以!

解决方案: 将this指针作为参数传递给静态函数,这样可以通过该this指针访问所有的私有变量, 但是我要是还需要向静态函数中传递我自己需要的参数呢?

答案是:将this指针和需要的参数作为一个结构体一起传给静态函数,请看下面代码:

view plain
copy to clipboard
print
?

#include <iostream>

#include "pthread.h"

using

namespace
std;

class
A;

struct
ARG

{

A* pThis;

string var;

};

class
A

{

public
:

A();

~A();

static

void
*
thread
(
void
* args);

void
excute();

private
:

int
iCount;

};

A::A()

{

iCount = 10;

}

A::~A()

{

}

void
* A::
thread
(
void
* args)

{

ARG *arg = (ARG*)args;

A* pThis = arg->pThis;

string var = arg->var;

cout<<"传入进来的参数var: "
<<var<<endl;

cout<<"用static线程函数调用私有变量: "
<<pThis->iCount<<endl;

}

void
A::excute()

{

int
error;

pthread_t thread_id;

ARG *arg = new
ARG();

arg->pThis = this
;

arg->var = "abc"
;

error = pthread_create(&thread_id, NULL, thread
, (
void
*)arg);

if
(error == 0)

{

cout<<"线程创建成功"
<<endl;

pthread_join(thread_id, NULL);

}

}

int
main()

{

A a;

a.excute();

return
0;

}

#include <iostream>
#include "pthread.h"
using namespace std;
class A;
struct ARG
{
A* pThis;
string var;
};
class A
{
public:
A();
~A();
static void* thread(void* args);
void  excute();
private:
int iCount;
};
A::A()
{
iCount = 10;
}
A::~A()
{
}
void* A::thread(void* args)
{
ARG *arg = (ARG*)args;
A* pThis = arg->pThis;
string var = arg->var;
cout<<"传入进来的参数var: "<<var<<endl;
cout<<"用static线程函数调用私有变量: "<<pThis->iCount<<endl;
}
void A::excute()
{
int error;
pthread_t thread_id;
ARG *arg = new ARG();
arg->pThis = this;
arg->var = "abc";
error = pthread_create(&thread_id, NULL, thread, (void*)arg);
if (error == 0)
{
cout<<"线程创建成功"<<endl;
pthread_join(thread_id, NULL);
}
}
int main()
{
A a;
a.excute();
return 0;
}


上述代码在G++下编译通过, 本篇小总结基本涵盖了线程函数在类中封装的问题。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: