gpt4 book ai didi

c++ - linux pthread - 有没有办法不将所有成员创建为静态成员?

转载 作者:太空狗 更新时间:2023-10-29 23:01:18 26 4
gpt4 key购买 nike

我正在使用 pthread 创建线程(在 C++ 应用程序中):

int result = pthread_create( &thread, NULL, CMyClass::RunThread, 0);

和 CMyClass::RunThread 必须是静态函数(以便编译):

static void *RunThread(void *ptr);

因此从 RunThread 调用的所有类成员和辅助函数也必须是静态的。

看来我有很多(~5)个静态成员。 (对我来说似乎不是一个好的编程...)

还有更好的办法吗?更优雅的方式?

谢谢

最佳答案

  1. 将这个指针传递给 pthread_create
  2. 启动一个 stub 函数来解决这个问题
  3. 调用你的真实函数

伪代码如下所示:

// static stub function
void* MyClass::thread_stub(void* p) {
MyClass* c = static_cast<MyClass*>(p);
return c->thread_func();
}

void* MyClass::thread_func() {
return NULL;
}

int MyClass::start() {
pthread_create(....thread_stub, this);
}

关于c++ - linux pthread - 有没有办法不将所有成员创建为静态成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31503588/

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