Qt:用 __thread 關鍵字讓每個線程有自己的全局變量


版權聲明:本文為博主原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接和本聲明。
本文鏈接:https://blog.csdn.net/wsj18808050/article/details/51603006
在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();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
輸出結果:

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)")
————————————————
版權聲明:本文為CSDN博主「Jason188080501」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/wsj18808050/article/details/51603006


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM