新建的工程,就只是建了2个线程,并且2个线程在运行。对2个线程需要进入的函数MainWindow::TestThread1()、MainWindow::TestThread2()设了断点,按F10几十次后,程序就报“底层由于接收到操作系统的信号而停止,信号名称:SIGSEGV 信号含义:Segmentation fault”。源码:
MainWindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QMutex>
#include "cthread1.h"
#include "cthread2.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
public:
int TestThread1();
int TestThread2();
private:
Ui::MainWindow *ui;
QMutex m_mutex1;
QMutex m_mutex2;
CThread1 thread1;
CThread2 thread2;
};
#endif // MAINWINDOW_H
MainWindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow),
m_mutex1(QMutex::Recursive),
m_mutex2(QMutex::Recursive),
thread1(this),
thread2(this)
{
ui->setupUi(this);
thread1.start();
thread2.start();
}
MainWindow::~MainWindow()
{
delete ui;
}
int MainWindow::TestThread1()
{
QMutexLocker locker(&m_mutex1);
static int a = 0;
a++;
return a;
}
int MainWindow::TestThread2()
{
QMutexLocker locker(&m_mutex2);
static int a = 0;
a++;
return a;
}
CThread1.cpp
#include "cthread1.h"
#include "mainwindow.h"
CThread1::CThread1(QObject *parent) :
QThread(parent)
{
}
void CThread1::run()
{
while(true)
{
MainWindow* w = (MainWindow*)this->parent();
w->TestThread1();
msleep(200);
}
}
CThread2.cpp
#include "cthread2.h"
#include "mainwindow.h"
CThread2::CThread2(QObject *parent) :
QThread(parent)
{
}
void CThread2::run()
{
while(true)
{
MainWindow* w = (MainWindow*)this->parent();
w->TestThread2();
msleep(200);
}