gpt4 book ai didi

c++ - 创建非静态成员函数的 pthread

转载 作者:太空宇宙 更新时间:2023-11-04 12:12:08 25 4
gpt4 key购买 nike

我有以下类(class):

class Foo {
private:
Bar *_bar;
void *run(void *);

public:
Foo(Bar *bar);
}

我希望 Foo::Foo 启动一个运行 Foo::run 的线程。

我知道这可以使用 std::thread 来完成:

Foo::Foo(Bar *bar) : _bar(bar) {
_thread = std::thread(&Foo::run, this);
}

问题是我需要为此线程设置优先级和调度策略 - 这可以使用 pthread 来实现。

(非常)遗憾的是,我无法更改系统的设计,我必须在 C'tor 中生成线程

pthread 是一个 C API,我不知道如何在非静态成员函数上运行它。以下尝试未编译:

Foo::Foo*(Bar *bar) : _bar(bar) {
// attempt 1
pthread_create(&thread, NULL, &Foo::run, this);
// attempt 2
pthread_create(&thread, NULL, (void* (*)(void *))(&Foo::run), this);
}

来自 pthread_create 手册页 - 第三个参数 (start_routine) 是指向返回 void * 和接收 的函数的指针无效 *

最佳答案

C 和 C++ 的调用约定完全不同,因为 C++ 函数(除非是静态函数)需要知道用哪个类实例调用其成员函数。

你能做的就是有一个静态函数,传入的参数是实例指针。像这样:

class Foo
{
private:
Bar *_bar;

static void *start_thread(void *ptr) { return dynamic_cast<MyThread *>(ptr)->run(); }

void *run(); // Implement thread here.

public:
Foo(Bar *bar);
}

Foo::Foo(Bar *bar) : _bar(bar) {
pthread_create(&thread, NULL, Foo::start_thread, this);
}

关于c++ - 创建非静态成员函数的 pthread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48561692/

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