gpt4 book ai didi

C++线程问题

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

我正在尝试使用以下代码在 C++ 中创建一个线程:

pthread_t mythread;
void* f (void*) = MyClass::myfunction;
pthread_create(&mythread, NULL, &f, NULL);

它不起作用。知道出了什么问题吗?

我的函数是这样的类型:

void* MyClass::myfunction(void* argv);

返回的错误是:

error: declaration of ‘void* Class::f(void*)’ has ‘extern’ and is initialized

error: invalid pure specifier (only ‘= 0’ is allowed) before ‘::’ token

error: function ‘void* Class::f(void*)’ is initialized like a variable

最佳答案

您将 f 声明为函数而不是函数指针。应该是:

void* (*f) (void*) = &MyClass::myfunction;
^^^^

pthread_create(&mythread, NULL, f, NULL);
^ no & since it's already a pointer

这也仅在 myfunction 是静态的情况下才有效,因为您无法将指向成员函数的指针转换为指向函数的指针。

如果您确实需要线程在特定对象上执行非静态成员函数,那么一种方法是编写一个将对象作为参数的静态包装器:

class MyClass {
public:
void start_thread() {
// Pass "this" to the thread we're creating
pthread_create(&mythread, NULL, &MyClass::thread_entry, this);
}
private:
static void * thread_entry(void * object) {
// Call the member function on the object passed to the thread
return static_cast<MyClass*>(object)->thread();
}
void * thread() {
// do the interesting stuff, with access to the member variables
}
};

当然,现在有一个标准的线程库可以消除这种舞蹈的需要:

std::thread thread(&MyClass::thread, this);

关于C++线程问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11327330/

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