オブジェクトを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
正しく使用していますか?そして、私の2番目の質問はvirtual void *thread_routine(void *arg)
、渡されたvoidポインターをへのポインターにコピーする最初の行が必要ProtectedBuffer
ですか?
また、問題を引き起こす可能性のある他のことをした場合は、それを聞いていただければ幸いです。