1//
2// ThreadLocalTest.cpp
3//
4// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
5// and Contributors.
6//
7// SPDX-License-Identifier: BSL-1.0
8//
9
10
11#include "ThreadLocalTest.h"
12#include "Poco/CppUnit/TestCaller.h"
13#include "Poco/CppUnit/TestSuite.h"
14#include "Poco/ThreadLocal.h"
15#include "Poco/Thread.h"
16#include "Poco/Runnable.h"
17
18
19using Poco::ThreadLocal;
20using Poco::Thread;
21using Poco::Runnable;
22
23
24class TLTestRunnable: public Runnable
25{
26public:
27 TLTestRunnable(int n): _n(n)
28 {
29 }
30
31 void run()
32 {
33 *_count = 0;
34 for (int i = 0; i < _n; ++i)
35 ++(*_count);
36 _result = *_count;
37 }
38
39 int result()
40 {
41 return _result;
42 }
43
44private:
45 int _n;
46 int _result;
47 static ThreadLocal<int> _count;
48};
49
50
51struct TLTestStruct
52{
53 int i;
54 std::string s;
55};
56
57
58ThreadLocal<int> TLTestRunnable::_count;
59
60
61ThreadLocalTest::ThreadLocalTest(const std::string& rName): CppUnit::TestCase(rName)
62{
63}
64
65
66ThreadLocalTest::~ThreadLocalTest()
67{
68}
69
70
71void ThreadLocalTest::testLocality()
72{
73 TLTestRunnable r1(5000);
74 TLTestRunnable r2(7500);
75 TLTestRunnable r3(6000);
76 Thread t1;
77 Thread t2;
78 Thread t3;
79 t1.start(r1);
80 t2.start(r2);
81 t3.start(r3);
82 t1.join();
83 t2.join();
84 t3.join();
85
86 assertTrue (r1.result() == 5000);
87 assertTrue (r2.result() == 7500);
88 assertTrue (r3.result() == 6000);
89}
90
91
92void ThreadLocalTest::testAccessors()
93{
94 ThreadLocal<TLTestStruct> ts;
95 ts->i = 100;
96 ts->s = "foo";
97 assertTrue ((*ts).i == 100);
98 assertTrue ((*ts).s == "foo");
99 assertTrue (ts.get().i == 100);
100 assertTrue (ts.get().s == "foo");
101}
102
103
104void ThreadLocalTest::setUp()
105{
106}
107
108
109void ThreadLocalTest::tearDown()
110{
111}
112
113
114CppUnit::Test* ThreadLocalTest::suite()
115{
116 CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ThreadLocalTest");
117
118 CppUnit_addTest(pSuite, ThreadLocalTest, testLocality);
119 CppUnit_addTest(pSuite, ThreadLocalTest, testAccessors);
120
121 return pSuite;
122}
123