【问题标题】:pthread without static decelaration with classpthread 没有带类的静态声明
【发布时间】:2019-10-16 00:12:42
【问题描述】:

在类中我声明了线程函数。我使用了 static 关键字,因为没有 static 关键字它不适用于类。

但是如果函数的类型是静态的,我就无法访问类的成员函数和公共变量

#include <iostream>
#include <pthread.h>
using namespace std;

class Base{

private:
    static  void * fpga_read(void*); // Thread function
    void foo_2();
public:
    /* member variables */
    void foo(void);

protected:
    int b;
};


void Base::foo(void)
{
    pthread_t id;
    pthread_create(&id, NULL,fpga_read,NULL);
    cout << "\nInside base class" << endl;
}
void * Base::fpga_read(void *p)
{
    cout << "\nInside thread function " << endl;
    // error: invalid use of member ‘Base::b’ in static member function
    cout << "Value of B inside thread class" << b;

    int b;
}

int main()
{
    Base a;
    a.foo();

    pthread_exit(NULL);
    return 0;
}

任何人告诉我如何在没有静态关键字的情况下使用线程函数。所以我可以访问所有的类变量。

【问题讨论】:

  • 您必须直接使用 pthreads 还是允许使用任何 C++11 类,例如 std::thread?
  • 是的,如果你想使用类成员,这个方法不能是静态的,尝试使用 pointer to method 从这个:stackoverflow.com/questions/1485983/…
  • 您是否查看过任何documentation of pthread_create 以了解其参数是什么以及是否可以使用它们?

标签: c++ linux multithreading pthreads


【解决方案1】:

您不需要任何静态成员函数。您可以使用pthread_create 的自变量参数,并将无状态 lambda 函数衰减为普通函数指针,以使代码看起来几乎与您实际编写的代码一样:

天箭链接:https://godbolt.org/z/QIGNUX


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

class Base {
public:
    Base(int state) noexcept : b{state} {}

    void foo();

private:
    int b;

    void fpga_read() {
        std::cout << "Value of B inside thread class" << b;
    }
};

void Base::foo()
{
    pthread_t thread;
    pthread_create(&thread, nullptr, [](void* that) -> void* {
        Base* this_ = static_cast<Base*>(that);
        this_->fpga_read();
        return nullptr;
    }, static_cast<void*>(this));
    pthread_join(thread, nullptr);
}

【讨论】:

  • thread_2.cpp:6: error: expected ‘;’ before ‘noexcept’ thread_2.cpp:6: error: expected ‘;’在'{'令牌thread_2.cpp:6之前:错误:'{'令牌thread_2.cpp之前的预期不合格ID:在成员函数'void Base :: foo()'中:thread_2.cpp:21:错误:'nullptr'未在此范围内声明 thread_2.cpp:21:错误:“[”标记 thread_2.cpp:21 之前的预期主表达式:错误:“]”标记 thread_2.cpp:21 之前的预期主表达式:错误:预期主表达式-'void' thread_2.cpp:21 之前的表达式:错误:'void'之前的预期 unqualified-id
  • 听起来您正在尝试编译为c++03 标准。尝试-std=c++11(或您的编译器的等效项)。
【解决方案2】:

pthread_create 与所有特定于操作系统的线程创建 API(Windows 中的 CreateThread 等)一样,都有一个“void*”参数来传递给线程函数。

你可以使用它来传递一个指向你的类的指针

class A
{
    void ThreadToUse() {}
    static void Thread2(void* p) 
    {
        A* a = (A*)p;
        p->ThreadToUse();
    }

    void foo()
    {
        pthread_create(&A::Thread2,(void*)this);
    }
};

也就是说,您也可以以标准方式使用具有相同功能的 C++11 std::thread

void foo()
{
    std::thread t(&A::Thread2,this);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多