Qt:用 __thread 关键字让每个线程有自己的全局变量

在GUN标准中,提供了__thread关键字,配合static后,可以实现让一个线程拥有自己的全局变量。

我对__thread进行了简单的封装,可以用于存储class。并且防止了内存泄露(如果使用Qt线程类)。

测试中,我一共开启了两个线程,从输出可以得知每个线程都拥有自己的变量,并且在线程退出后被正常释放。

测试代码:

// Qt lib import
#include <QtCore>
#include <QtConcurrent>

class MyClass
{
public:
    MyClass()
    {
        qDebug() << "MyClass" << this << QThread::currentThread();
    }

    ~MyClass()
    {
        qDebug() << "~MyClass" << this << QThread::currentThread();
    }
};

template< class T >
class ThreadStore
{
public:
    T &getQuote()
    {
        if ( !t )
        {
            t = new T;

            auto thread = qobject_cast< QThread * >( QThread::currentThread() );
            if ( thread && thread->isRunning() )
            {
                QObject::connect( QThread::currentThread(), &QThread::finished, [ this ]()
                {
                    if ( t )
                    {
                        delete t;
                        t = nullptr;
                    }
                } );
            }
        }

        return *t;
    }

private:
    T *t;
};

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    auto myTest = []()
    {
        static __thread ThreadStore< MyClass > threadStore;

        auto &myData = threadStore.getQuote();

        qDebug() << "myData:" << &myData;

        QThread::sleep( 1 );
    };

    QThreadPool::globalInstance()->setMaxThreadCount( 2 );

    QtConcurrent::run( myTest );
    QtConcurrent::run( myTest );
    QtConcurrent::run( myTest );
    QtConcurrent::run( myTest );

    QThreadPool::globalInstance()->waitForDone();

    return a.exec();
}

输出结果:

MyClass 0x7fe842e09b10 QThread(0x7fe842d0cbe0, name = "Thread (pooled)")
MyClass 0x7fe842c1d6a0 QThread(0x7fe842d0df60, name = "Thread (pooled)")
myData: 0x7fe842e09b10
myData: 0x7fe842c1d6a0
myData: 0x7fe842e09b10
myData: 0x7fe842c1d6a0
~MyClass 0x7fe842e09b10 QThread(0x7fe842d0cbe0, name = "Thread (pooled)")
~MyClass 0x7fe842c1d6a0 QThread(0x7fe842d0df60, name = "Thread (pooled)")
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值