gpt4 book ai didi

c++ - 强制转换为 void* 以将对象传递给 C++ 中的 pthread

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:30:38 24 4
gpt4 key购买 nike

我对如何将对象传递给 pthread_create 函数有些困惑。我发现了很多关于转换为 void*、将参数传递给 pthread_create 等的零碎信息,但没有任何内容将它们联系在一起。我只是想确保我已经把它们绑在一起并且没有做任何愚蠢的事情。假设我有以下线程类:编辑:修复了不匹配的 static_cast

class ProducerThread {
pthread_t thread;
pthread_attr_t thread_attr;
ProducerThread(const ProducerThread& x);
ProducerThread& operator= (const ProducerThread& x);
virtual void *thread_routine(void *arg) {
ProtectedBuffer<int> *buffer = static_cast<ProtectedBuffer<int> *> arg;
int randomdata;

while(1) {
randomdata = RandomDataGen();
buffer->push_back(randomdata);
}

pthread_exit();
}
public:
ProtectedBuffer<int> buffer;

ProducerThread() {
int err_chk;

pthread_attr_init(&thread_attr);
pthread_attr_setdetachstate(&thread_attr,PTHREAD_CREATE_DETACHED);

err_chk = pthread_create(&thread, &thread_attr, thread_routine, static_cast<void *> arg);
if (err_chk != 0) {
throw ThreadException(err_chk);
}
}
~ProducerThread() {
pthread_cancel(&thread);
pthread_attr_destroy(&thread_attr);
}
}

需要说明的是,ProtectedBuffer 类中的数据只能通过 ProtectedBuffer::push_back(int arg) 等方法访问,这些方法使用互斥锁来保护实际数据.

我的主要问题是:我是否正确使用了 static_cast?我的第二个问题是我是否需要 virtual void *thread_routine(void *arg) 中的第一行,我将传递的 void 指针复制到指向 ProtectedBuffer 的指针?

此外,如果我做了任何其他可能会导致问题的事情,我将不胜感激。

最佳答案

您的代码存在许多问题。对于初学者,我不看看你正在转换的 arg 在哪里声明,所以我不能说是否这种情况是合适的。

也许更重要的是,thread_routine 是一个成员函数,所以它不能转换为指向函数的指针。传递给的函数pthread_create 必须是 extern "C",所以它不能是成员,句号;它必须是一个自由函数 declare extern "C"。如果你想调用成员函数,将指向对象的指针作为最后一个参数传递,并且在 extern "C" 函数中取消引用它:

extern "C" void* startProducerThread( void* arg )
{
return static_cast<ProducerThread*>( arg )->thread_routine();
}

开始线程:

int status = pthread_create( &thread, &thread_attr, startProducerThread, this );

只是不要在构造函数中这样做。另一个线程可能会启动在对象完全构建之前运行,具有灾难性效果。

此外,请务必确保 startProducerThread 中的转换是为了完全与传递给 pthread_create 的指针类型相同。如果你转换为 startProducerThread 中的基类,然后非常非常确保它是指向您传递给的基类的指针pthread_create;如有必要,使用显式转换(到类型startProducerThreadvoid*)。

最后,虽然与您的实际问题无关:如果ProtectedBuffer 有一个类似于 std::vector 的接口(interface),并且返回对内部数据的引用,你无法做到线程安全。保护需要在类之外。

关于c++ - 强制转换为 void* 以将对象传递给 C++ 中的 pthread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11871299/

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