QT开发之多线程
来源:互联网 发布:不用网络的赛车游戏 编辑:程序博客网 时间:2024/06/05 20:19
在Linux中我们经常使用多线程编程,同时就会提出同步和异步操作.像原子变量,信号量,阻塞,自旋锁,互斥所等,在Qt中也有类似的概念,但是在我的开发中用的不是很多,下面列举一下多线程编程的基础.
新建一个Gui应用项目,代码注释的非常详细.
创建线程后,启动线程默认是run函数,除非有特殊指定
dialog.h
#ifndef DIALOG_H#define DIALOG_H#include <QDialog>#include <QThread>namespace Ui {class Dialog;}class MyThread : public QThread{ Q_OBJECTpublic: explicit MyThread(QObject *parent = 0); void stop();protected: void run();private: volatile bool stopped; int shareValue;signals:public slots:};class Dialog : public QDialog{ Q_OBJECT public: explicit Dialog(QWidget *parent = 0); ~Dialog(); private slots: void on_startButton_clicked(); void on_stopButton_clicked(); void on_startButton_2_clicked(); void on_stopButton_2_clicked();private: Ui::Dialog *ui; MyThread thread1,thread2;};#endif // DIALOG_H
dialog.cpp
#include "dialog.h"#include "ui_dialog.h"#include <QDebug>/* A B线程共同去访问某一资源测试 */Dialog::Dialog(QWidget *parent) : QDialog(parent), ui(new Ui::Dialog){ ui->setupUi(this); //connect(&thread1,SIGNAL(started()),this,SLOT(startThread1())); //connect(&thread1,SIGNAL(finished()),this,SLOT(stopThread1()));}Dialog::~Dialog(){ delete ui;}MyThread::MyThread(QObject *parent) : /* 构造函数 */ QThread(parent){ stopped = false; shareValue = 0;}void MyThread::run() /* start()函数默认会调用run()函数 */{ //int i = 0; while (!stopped){ //qDebug() << QString("in MyThread: %1").arg(i++); msleep(1000); qDebug() << "shareValue" << shareValue++ << endl; //i++; } stopped = false;}void MyThread::stop(){ stopped = true;}/* A线程操作 */void Dialog::on_startButton_clicked(){ thread1.start(); //thread.wait() /* 同步终止 */ ui->startButton->setEnabled(false); ui->stopButton->setEnabled(true); //int Thread = thread1.currentThreadId();}void Dialog::on_stopButton_clicked(){ if(thread1.isRunning()){ thread1.stop(); ui->startButton->setEnabled(true); ui->stopButton->setEnabled(false); }}/* B 线程操作 */void Dialog::on_startButton_2_clicked(){ thread2.start(); //thread.wait() /* 同步终止 */ ui->startButton_2->setEnabled(false); ui->stopButton_2->setEnabled(true);}void Dialog::on_stopButton_2_clicked(){ if(thread2.isRunning()){ thread2.stop(); ui->startButton_2->setEnabled(true); ui->stopButton_2->setEnabled(false); }}
界面效果:
3 0
- QT开发之多线程
- Qt之多线程(一)
- Qt之多线程(二)
- Qt之多线程-QMutex
- IOS开发之多线程
- iOS开发之多线程
- iOS开发之多线程
- iOS开发之多线程
- iOS开发之多线程
- iOS开发之多线程
- Revit开发之多线程
- iOS开发之多线程
- Android开发之多线程
- iOS开发之多线程
- Qt之多线程QThread简介
- Qt之多线程(三)
- Qt之多线程(四)
- Qt之多线程(五)
- 二:Java语言基础组成—— 标识符
- equals方法重写详解
- 软件设计是怎样炼成的(7)——细节决定成败(详细设计)
- 大端机和小端机区别
- HTML 固定div于页面固定位置,实现悬浮按钮。
- QT开发之多线程
- java基础-Stringbuffer转义字符
- 计算组合数
- 1613-3-傅溥衍 总结《2016年12月14日》【连续第七十五天总结】
- 软件设计是怎样炼成的(8)——用户感觉好才是真的好(用户体验设计)
- 静态类 - static
- easonguo test
- sqlmap 的源码学习笔记一之目录结构
- Java 8 Stream API features --- filter/reduce & predicate Interface test method