从pthread访问外部类变量

时间:2016-09-10 14:08:27

标签: c++ multithreading variables pthreads

我正在用C ++编写一个程序,它要求我使用几个类和线程来处理手头的问题。这是一个简化的剪辑:

主类:初始化eth_controllerpt_proc_data并调用以启动工作线程StartParsePacket

class MFA_MAIN : public QMainWindow
    {
        Q_OBJECT
    public:
        MFA_MAIN(QWidget *parent = 0);
        ~MFA_MAIN();
    private:
        Ui::MFA_MAINClass ui;
        eth_controller* eth;
        pt_proc_data *pd;
    }
    MFA_MAIN::MFA_MAIN(QWidget *parent)
        : QMainWindow(parent)
    {
        eth = new eth_controller(ui.txtStatus, ui.cmbEthernetPort);
        pd = new pt_proc_data(PSD, eth, this);
        pd->StartParsePacket(ui.txtStatus);
    }

在此阶段,以太网类仅进行初始化,因此bool ok设置为false,表示设备处理程序尚未正确设置:

class eth_controller : public QThread
{
    Q_OBJECT

public:
    eth_controller(QPlainTextEdit * status, QComboBox* list);
    ~eth_controller();
    bool ok;
}
eth_controller::eth_controller(QPlainTextEdit * status, QComboBox* list)
{
    ok = false;
......
}

工作者类:他将启动一个新的pthread来开始解析。但首先他检查以太网类中的ok变量是否正确设置:

class pt_proc_data 
{
public:
    pt_proc_data(data_ty t, eth_controller *e, QObject *g);
    ~pt_proc_data();

    //thread
    void *doParsePacket();
    //thread heplers
    static void *hParsePacket(void* ctx);
    //thread starters
    void StartParsePacket(QPlainTextEdit *status);


 private:
        //plot bins
....
        //parsing tools
        eth_controller *eth;
        vector<S> PayQueue;
        QObject* ptr_gui;

    //thread control
    pthread_t threads[3];
    bool init[3];
    pthread_mutex_t PlotLock;
    pthread_mutex_t QueueLock;
    pthread_mutex_t ResetLock;
    pthread_mutex_t ToggleLock;
    data_ty _type;
    bool _running = false;
    bool _end = false;
    int _freq;
    ofstream fd;
    bool _log;
}

pt_proc_data::pt_proc_data(data_ty t, eth_controller *e, QObject* g)
{
    _type = t; eth = e; ptr_gui = g;
}
void pt_proc_data::StartParsePacket(QPlainTextEdit *status)
{
    int rc;
    if (pthread_create(&threads[0], NULL, &pt_proc_data::hParsePacket, this)) {
        status->appendPlainText("StartParsePacket Error:unable to create thread");
        return;
    }
    return;
}
void *pt_proc_data::hParsePacket(void* ctx)
{
    pt_proc_data *context = static_cast<pt_proc_data*>(ctx);
    context->doParsePacket();
    delete context;
    return 0;
    //return ((pt_proc_data *)ctx)->doParsePacket();
}
void *pt_proc_data::doParsePacket()
{
    if (!eth->ok)
    {
        QMetaObject::invokeMethod(ptr_gui, "setStatusText",
            Q_ARG(QString, "payload download: Device not setup correctly."));
        pthread_exit(NULL);
    }
    QMetaObject::invokeMethod(ptr_gui, "setStatusText",
        Q_ARG(QString, "doParsePacket: started."));
.......
}

线程正确启动。在此阶段设备设置不正确,因此doParsePacket()应始终找到eth->ok = false,并抱怨设备设置不正确。但如果我启动程序10次,4-5次,就会发现eth->ok的值为true !!!!!

我想知道有人可以告诉我为什么会这样。谢谢

1 个答案:

答案 0 :(得分:0)

确定。我找到了解决方案。我将bool ok;声明为private并添加了bool isOk() {return ok;};,现在似乎正在运作。

但我不明白为什么会这样。也许有人可以解决一些问题