]> git.saurik.com Git - apple/icu.git/blame - icuSources/test/intltest/simplethread.cpp
ICU-64243.0.1.tar.gz
[apple/icu.git] / icuSources / test / intltest / simplethread.cpp
CommitLineData
f3c0d7a5
A
1// © 2016 and later: Unicode, Inc. and others.
2// License & terms of use: http://www.unicode.org/copyright.html
729e4ab9
A
3/********************************************************************
4 * COPYRIGHT:
2ca993e8 5 * Copyright (c) 1999-2015, International Business Machines Corporation and
729e4ab9
A
6 * others. All Rights Reserved.
7 ********************************************************************/
8
4388f060 9
729e4ab9
A
10#include "simplethread.h"
11
3d1f044b 12#include <thread>
729e4ab9 13#include "unicode/utypes.h"
51004dcb 14#include "intltest.h"
729e4ab9 15
729e4ab9 16
3d1f044b 17SimpleThread::SimpleThread() {
729e4ab9
A
18}
19
3d1f044b
A
20SimpleThread::~SimpleThread() {
21 this->join(); // Avoid crashes if user neglected to join().
729e4ab9
A
22}
23
3d1f044b
A
24int SimpleThread::start() {
25 fThread = std::thread(&SimpleThread::run, this);
26 return fThread.joinable() ? 0 : 1;
729e4ab9
A
27}
28
2ca993e8 29void SimpleThread::join() {
3d1f044b
A
30 if (fThread.joinable()) {
31 fThread.join();
729e4ab9 32 }
729e4ab9
A
33}
34
729e4ab9 35
2ca993e8
A
36
37class ThreadPoolThread: public SimpleThread {
38 public:
39 ThreadPoolThread(ThreadPoolBase *pool, int32_t threadNum) : fPool(pool), fNum(threadNum) {};
40 virtual void run() {fPool->callFn(fNum); }
41 ThreadPoolBase *fPool;
42 int32_t fNum;
43};
44
45
46ThreadPoolBase::ThreadPoolBase(IntlTest *test, int32_t howMany) :
47 fIntlTest(test), fNumThreads(howMany), fThreads(NULL) {
48 fThreads = new SimpleThread *[fNumThreads];
49 if (fThreads == NULL) {
50 fIntlTest->errln("%s:%d memory allocation failure.", __FILE__, __LINE__);
51 return;
729e4ab9 52 }
2ca993e8
A
53
54 for (int i=0; i<fNumThreads; i++) {
55 fThreads[i] = new ThreadPoolThread(this, i);
56 if (fThreads[i] == NULL) {
57 fIntlTest->errln("%s:%d memory allocation failure.", __FILE__, __LINE__);
58 }
729e4ab9 59 }
729e4ab9
A
60}
61
2ca993e8
A
62void ThreadPoolBase::start() {
63 for (int i=0; i<fNumThreads; i++) {
64 if (fThreads && fThreads[i]) {
65 fThreads[i]->start();
66 }
67 }
68}
729e4ab9 69
2ca993e8
A
70void ThreadPoolBase::join() {
71 for (int i=0; i<fNumThreads; i++) {
72 if (fThreads && fThreads[i]) {
73 fThreads[i]->join();
74 }
75 }
76}
729e4ab9 77
2ca993e8
A
78ThreadPoolBase::~ThreadPoolBase() {
79 if (fThreads) {
80 for (int i=0; i<fNumThreads; i++) {
81 delete fThreads[i];
82 fThreads[i] = NULL;
83 }
84 delete[] fThreads;
85 fThreads = NULL;
729e4ab9 86 }
2ca993e8 87}