gpt4 book ai didi

c++ - 使用 pthread_create 从线程调用类成员函数

转载 作者:行者123 更新时间:2023-11-30 01:10:24 32 4
gpt4 key购买 nike

下面是代码

#include <iostream>
#include <pthread.h>

using namespace std;

class Base

{
private:
public:

void *threadCall1( void * value)
{
cout<<"inside threadCall1"<<endl;

}

protected:

};

class Derived
{
private:
public:
void *threadCall2 ();
protected:



};


void *Derived::threadCall2()
{
cout<<"inside threadCall2"<<endl;

}
int main ()
{
int k = 2;
pthread_t t1;
cout<<"inside main"<<endl;
Base *b = new Base();

pthread_create(&t1,NULL,&b->threadCall1,(void *)k);

return 0;
}

错误

main.cc: In function int main()': main.cc:46: error: ISO C++ forbids
taking the address of a bound member function to form a pointer to
member function. Say
&Base::threadCall1' main.cc:46: error: cannot convert void*(Base::*)(void*)' tovoid*()(void)' for argument 3'
to
int pthread_create(pthread_t*, const pthread_attr_t*, void*()(void), void*)'

我同意 C++ 禁止此调用,但有什么方法可以使用 posix 线程调用类成员函数

最佳答案

您可以通过相应地分派(dispatch)工作的函数来执行此操作:

#include <iostream>
#include <pthread.h>

struct Base {
virtual void work() {
std::cout << "Base::work()\n";
}

virtual ~Base() {}
};

struct Derived : public Base {
void work() override {
std::cout << "Derived::work()\n";
}
};

void* thread_adapter(void* obj) {
Base* p = static_cast<Base*>(obj);
p->work();
return nullptr;
}

int main() {
Derived d;
pthread_t thread;
pthread_create(&thread, nullptr, thread_adapter, &d);
pthread_join(thread, nullptr);
}

Live example

pthread_create 接受指向线程函数的任意数据的指针。传递对象的地址,并使用转发函数,例如上面定义的 thread_adapter。在适配器函数内部,您可以将参数 static_cast 返回到线程函数内部的 Base* 并根据需要调用成员函数。

但是,您可能需要查看 std::thread库,以更自然的方式支持此类操作:

#include <iostream>
#include <thread>

struct Base {
virtual void work() {
std::cout << "Base::work()\n";
}

virtual ~Base() {}
};

struct Derived : public Base {
void work() override {
std::cout << "Derived::work()\n";
}
};

int main() {
Derived d;
std::thread t(&Base::work, d);
t.join();
}

Live example

关于c++ - 使用 pthread_create 从线程调用类成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37939606/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com