Vc- Qt - QThread

一、简单的使用线程

如何使用线程呢?通过继承QThread类,重载void run()函数,之后调用start函数启动线程即可

#include <QCoreApplication>
#include <QThread>
#include <QDebug>
class MyThread : public QThread
{
protected:
    void run()
    {
        for(int i=0; i<5; i++)
        {
            qDebug() << objectName() << " : " << i;
            sleep(1);
        }
    }
};
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    MyThread t;
    t.setObjectName("t");
    t.start();
 
    MyThread tt;
    tt.setObjectName("tt");
    tt.start();
 
    return a.exec();
}

二、线程增加开启和关闭线程标志位

class Sample : public QThread
{
protected:
    volatile bool m_toStop;
 
    void run()
    {
        int* p = new int[10000];
 
        for(int i=0; !m_toStop && (i<10); i++)
        {
            qDebug() << objectName() << " : " << i;
 
            p[i] = i * i * i;
 
            msleep(500);
        }
 
        delete[] p;  //内存泄漏
 
        qDebug() << objectName() << " : end";
    }
 
public:
    Sample()
    {
        m_toStop = false;
    }
 
    void stop()
    {
        m_toStop = true;
    }
};
 
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
 
    qDebug() << "main begin";
 
    Sample t;
 
    t.setObjectName("t");
 
    t.start();
 
    //for(int i=0; i<10000; i++)
    //{
      //  for(int j=0; j<10000; j++)
      //  {
 
        //}
    //}

    msleep(500*10);

    t.stop();  //执行后无内存泄漏
 
    //t.terminate();  //会在线程未结束时,杀死线程, 内存泄漏
 
    qDebug() << "main end";
 
    return a.exec();
}

三、生产者和消费者的一个例子

#include <QCoreApplication>
#include <QThread>
#include <QDebug>
#include <QMutex>
 
static QString g_store;
static QMutex g_mutex;
 
class Producer : public QThread
{
protected:
    void run()
    {
        int count = 0;
 
        while (true)
        {
            g_mutex.lock();
 
            g_store.append(QString::number((count++) % 10));  //将随机数字(0-9)存入仓库
 
            qDebug() << objectName() << " : " + g_store;
 
            g_mutex.unlock();
 
            msleep(1);
        }
    }
};
 
class Customer : public QThread
{
protected:
    void run()
    {
        while (true)
        {
            g_mutex.lock();
 
            if( g_store != "")
            {
                g_store.remove(0, 1);
 
                qDebug() << objectName() << " : " + g_store;
            }
 
            g_mutex.unlock();
 
            msleep(1);
        }
 
    }
};
 
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
 
    Producer p;
    Customer c;
 
    p.setObjectName("Producer");
    c.setObjectName("Customer");
 
    p.start();
    c.start();
 
    return a.exec();
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值