我的錯誤:爲什麼一個類的線程函數應該靜態地在同一個類中被訪問?
error: cannot convert 'MainWindow::producerThreadFunction' from type 'void* (MainWindow::)(void*)' to type 'void* (*)(void*)'
if (pthread_create (&producer, NULL, producerThreadFunction, NULL))
^
頭文件:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QApplication>
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/syscall.h>
#include <iostream>
#include <QDebug>
class MainWindow : public QMainWindow
{
Q_OBJECT
pthread_mutex_t mutexVariable = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t conditionVariable = PTHREAD_COND_INITIALIZER;
QList <int> queueLIFO;
public:
MainWindow(QWidget *parent = 0);
~MainWindow();
// This function is run by the thread `Producer`.
void *producerThreadFunction (void *arg);
// This function is run by the thread `Consumer`.
void *consumerThreadFunction (void *arg);
int start();
};
#endif // MAINWINDOW_H
源文件:(功能發生錯誤)
int MainWindow :: start()
{
pthread_t producer;
pthread_t consumer;
if (pthread_create (&producer, NULL, producerThreadFunction, NULL))
{
fprintf (stderr, "Error creating thread Producer\n");
return 1;
}
if (pthread_create (&consumer, NULL, consumerThreadFunction, NULL))
{
fprintf (stderr, "Error creating thread Consumer\n");
return 1;
}
if (pthread_join (producer, NULL))
{
fprintf (stderr, "Error joining thread Producer\n");
return 2;
}
if (pthread_join (consumer, NULL))
{
fprintf (stderr, "Error joining thread Consumer\n");
return 2;
}
return 0;
}
根據this thread,解決方案是使producerThreadFunction
靜態。
爲什麼一個類的線程函數應該是靜態的以便可以在同一個類中訪問?
該函數是該類的成員函數。爲什麼我不能直接訪問它?
只需使用標準的C++線程。 –
請注意,儘管大多數編譯器不會阻止您將靜態成員函數用作「C」函數,但它的語言綁定是錯誤的。而在標準C++中,它不能被聲明爲「extern」C「'。我似乎記得Sun的C++編譯器會默認提醒它。 –
@ Cheersandhth.-Alf好 - 我沒有意識到這一點。我做了一點挖掘,發現你是對的。我相應地更新了我的答案。 –