c++ - 新线程上的应用程序崩溃开始

标签 c++ multithreading qt

为什么这个应用程序在新线程启动时崩溃,请大家指出我是不是做错了什么..

新线程.h

   #ifndef NEWTHREAD_H
    #define NEWTHREAD_H
   #include <QThread>

    class newthread: public QThread
    {
        public:
           newthread();

        public slots:
            void run();
     };

     #endif // NEWTHREAD_H

新线程.cpp

    #include "newthread.h"
    #include "mainwindow.h"
    #include<QDebug>

     newthread::newthread()
     {
     }

    void newthread::run(){
       qDebug()<<"thread executed";
    } 

主窗口.cpp

    #include <QtGui>
       #include "mainwindow.h"
    #include"newthread.h"



     MainWindow::MainWindow(QWidget *parent)
     {
        setupUi(this);
      connect(pushButton,SIGNAL(clicked()),this, SLOT(opthread()));

       }

    void MainWindow::opthread(){
    newthread th;
     th.start();
     }

在主窗口中有一个名为 ophthread() 的公共(public)插槽。如上所示,当按下主窗口中的按钮时,该插槽将触发。在其中我声明了一个名为 th 和 th.start() 的新线程对象来启动它。我做错了什么吗?

这编译没有错误。但是当运行二进制文件时,它会出错并崩溃。

我的第二个问题是,如果我需要线程在主窗口的 textEdit 上写一些文本,该怎么做。有没有可能newthread类访问主窗口类中的对象。

最佳答案

void MainWindow::opthread(){
    newthread th;
    th.start();
 }

您正在堆栈上创建线程对象。当 opthread 函数返回时,他将被销毁。来自Qt documentation :

Deleting a running QThread (i.e. isFinished() returns false) will probably result in a program crash. Wait for the finished() signal before deleting the QThread.

您需要为新线程对象提供更长的生命周期。等待它完成不是一种选择,因为它会导致顺序执行。您要么使用类成员,要么在堆上分配线程对象。

个人观点: 不仅子类化 QThread 不是完成它的最合适的方法,我相信你根本不需要线程。

关于c++ - 新线程上的应用程序崩溃开始,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17400240/

相关文章:

c++ - 如何使用QtSingleApplication bt的so文件?

c++ - 根据正则表达式从 QT (C++) 中的 SQLite 数据库中检索记录

c++ - 内存管理模式

c++ - C++编译错误: expected initializer before ‘+=’ token

使用 100% 单 CPU 内核的 Java Web 应用程序

.net - 这段代码是线程安全的吗?

实现简单内存池的 C 库

c++ - Qt4,直接分配 QPainterPath 不起作用( Unresolved external 问题)

c++ - 使用 uBLAS 在 C++ 中从 vector 创建矩阵

C++ 内部 : Messing with the this-pointer