aboutsummaryrefslogtreecommitdiffstats
path: root/fastos/src/vespa/fastos/thread.cpp
blob: 9a9c3321cac8cc9e7fcec5c55b8a99134975f51c (plain) (blame)
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
//************************************************************************
/**
 * Implementation of FastOS_ThreadPool and FastOS_Thread methods.
 *
 * @author  Oivind H. Danielsen
 */

#include "thread.h"
#include <cstdio>
#include <cassert>

// ----------------------------------------------------------------------
// FastOS_ThreadPool
// ----------------------------------------------------------------------

FastOS_ThreadPool::FastOS_ThreadPool() : FastOS_ThreadPool(0) {}

FastOS_ThreadPool::FastOS_ThreadPool(int maxThreads)
    : _startedThreadsCount(0),
      _closeFlagMutex(),
      _closeCalledFlag(false),
      _freeMutex(),
      _liveMutex(),
      _liveCond(),
      _freeThreads(nullptr),
      _activeThreads(nullptr),
      _numFree(0),
      _numActive(0),
      _numTerminated(0),
      _numLive(0),
      _maxThreads(maxThreads)   // 0 means unbounded
{
}

FastOS_ThreadPool::~FastOS_ThreadPool(void)
{
    Close();
}

void FastOS_ThreadPool::ThreadIsAboutToTerminate(FastOS_ThreadInterface *)
{
    assert(isClosed());

    std::lock_guard<std::mutex> guard(_liveMutex);

    _numTerminated++;
    _numLive--;
    if (_numLive == 0) {
        _liveCond.notify_all();
    }
}


// This is a NOP if the thread isn't active.
void FastOS_ThreadPool::FreeThread (FastOS_ThreadInterface *thread)
{
    std::lock_guard<std::mutex> guard(_freeMutex);

    if(thread->_active) {
        LinkOutThread(thread, &_activeThreads);

        thread->_active = false;
        _numActive--;

        LinkInThread(thread, &_freeThreads);
        _numFree++;
    }
}

void FastOS_ThreadPool::LinkOutThread (FastOS_ThreadInterface *thread, FastOS_ThreadInterface **listHead)
{
    if (thread->_prev != nullptr)
        thread->_prev->_next = thread->_next;
    if (thread->_next != nullptr)
        thread->_next->_prev = thread->_prev;

    if (thread == *listHead)
        *listHead = thread->_next;
}

void FastOS_ThreadPool::LinkInThread (FastOS_ThreadInterface *thread, FastOS_ThreadInterface **listHead)
{
    thread->_prev = nullptr;
    thread->_next = *listHead;

    if (*listHead != nullptr)
        (*listHead)->_prev = thread;

    *listHead  = thread;
}


// _freeMutex is held by caller.
void FastOS_ThreadPool::ActivateThread (FastOS_ThreadInterface *thread)
{
    LinkOutThread(thread, &_freeThreads);
    LinkInThread(thread, &_activeThreads);

    thread->_active = true;
    _numActive++;
    _startedThreadsCount++;
}


// Allocate a thread, either from pool of free or by 'new'.  Finally,
// make this thread call parameter fcn when it becomes active.
FastOS_ThreadInterface *FastOS_ThreadPool::NewThread (FastOS_Runnable *owner, void *arg)
{
    FastOS_ThreadInterface *thread=nullptr;

    std::unique_lock<std::mutex> freeGuard(_freeMutex);

    if (!isClosed()) {
        if ((thread = _freeThreads) != nullptr) {
            // Reusing thread entry
            _freeThreads = thread->_next;
            _numFree--;

            ActivateThread(thread);
        } else {
            // Creating new thread entry

            if (_maxThreads != 0 && ((_numActive + _numFree) >= _maxThreads)) {
                fprintf(stderr, "Error: Maximum number of threads (%d)"
                        " already allocated.\n", _maxThreads);
            } else {
                freeGuard.unlock();
                {
                    std::lock_guard<std::mutex> liveGuard(_liveMutex);
                    _numLive++;
                }
                thread = FastOS_Thread::CreateThread(this);

                if (thread == nullptr) {
                    std::lock_guard<std::mutex> liveGuard(_liveMutex);
                    _numLive--;
                    if (_numLive == 0) {
                        _liveCond.notify_all();
                    }
                }
                freeGuard.lock();

                if(thread != nullptr)
                    ActivateThread(thread);
            }
        }
    }

    freeGuard.unlock();
    if(thread != nullptr) {
        std::lock_guard<std::mutex> liveGuard(_liveMutex);
        thread->Dispatch(owner, arg);
    }

    return thread;
}


void FastOS_ThreadPool::BreakThreads ()
{
    FastOS_ThreadInterface *thread;

    std::lock_guard<std::mutex> freeGuard(_freeMutex);

    // Notice all active threads that they should quit
    for(thread=_activeThreads; thread != nullptr; thread=thread->_next) {
        thread->SetBreakFlag();
    }

    // Notice all free threads that they should quit
    for(thread=_freeThreads; thread != nullptr; thread=thread->_next) {
        thread->SetBreakFlag();
    }
}


void FastOS_ThreadPool::JoinThreads ()
{
    std::unique_lock<std::mutex> liveGuard(_liveMutex);
    while (_numLive > 0) {
        _liveCond.wait(liveGuard);
    }
}

void FastOS_ThreadPool::DeleteThreads ()
{
    FastOS_ThreadInterface *thread;

    std::lock_guard<std::mutex> freeGuard(_freeMutex);

    assert(_numActive == 0);
    assert(_numLive == 0);

    while((thread = _freeThreads) != nullptr) {
        LinkOutThread(thread, &_freeThreads);
        _numFree--;
        //      printf("deleting thread %p\n", thread);
        delete(thread);
    }

    assert(_numFree == 0);
}

void FastOS_ThreadPool::Close ()
{
    std::unique_lock<std::mutex> closeFlagGuard(_closeFlagMutex);
    if (!_closeCalledFlag) {
        _closeCalledFlag = true;
        closeFlagGuard.unlock();

        BreakThreads();
        JoinThreads();
        DeleteThreads();
    }
}

bool FastOS_ThreadPool::isClosed()
{
    std::lock_guard<std::mutex> closeFlagGuard(_closeFlagMutex);
    bool closed(_closeCalledFlag);
    return closed;
}

extern "C"
{
void *FastOS_ThreadHook (void *arg)
{
    FastOS_ThreadInterface *thread = static_cast<FastOS_ThreadInterface *>(arg);
    thread->Hook();

    return nullptr;
}
};


// ----------------------------------------------------------------------
// FastOS_ThreadInterface
// ----------------------------------------------------------------------

void FastOS_ThreadInterface::Hook ()
{
    // Loop forever doing the following:  Wait on the signal _dispatched.
    // When awoken, call _start_fcn  with the parameters.  Then zero set
    // things and return this to the owner, i.e. pool of free threads
    bool finished=false;
    bool deleteOnCompletion = false;

    while(!finished) {

        std::unique_lock<std::mutex> dispatchedGuard(_dispatchedMutex); // BEGIN lock
        while (_owner == nullptr && !(finished = _pool->isClosed())) {
            _dispatchedCond.wait(dispatchedGuard);
        }

        dispatchedGuard.unlock();           // END lock

        if(!finished) {
            deleteOnCompletion = _owner->DeleteOnCompletion();
            _owner->Run(this, _startArg);

            dispatchedGuard.lock();         // BEGIN lock

            if (deleteOnCompletion) {
                delete _owner;
            }
            _owner = nullptr;
            _startArg = nullptr;
            _breakFlag.store(false, std::memory_order_relaxed);
            finished = _pool->isClosed();

            dispatchedGuard.unlock();      // END lock

            {
                std::lock_guard<std::mutex> runningGuard(_runningMutex);
                _runningFlag = false;
                _runningCond.notify_all();
            }

            _pool->FreeThread(this);
            // printf("Thread given back to FastOS_ThreadPool: %p\n", this);
        }
    }

    _pool->ThreadIsAboutToTerminate(this);

    // Be sure not to touch any members from here on, as we are about
    // to be deleted.
}


// Make this thread call parameter fcn with parameters argh
// when this becomes active.
// Restriction: _liveCond must be held by the caller.

void FastOS_ThreadInterface::Dispatch(FastOS_Runnable *newOwner, void *arg)
{
    std::lock_guard<std::mutex> dispatchedGuard(_dispatchedMutex);

    {
        std::unique_lock<std::mutex> runningGuard(_runningMutex);
        while (_runningFlag) {
            _runningCond.wait(runningGuard);
        }
        _runningFlag = true;
    }

    _owner = newOwner;
    _startArg = arg;
    // Set _thread variable before NewThread returns
    _owner->_thread.store(this, std::memory_order_release);

    // It is safe to signal after the unlock since _liveCond is still held
    // so the signalled thread still exists.
    // However as thread creation is infrequent and as helgrind suggest doing
    // it the safe way we just do that, instead of keeping a unneccessary long
    // suppressionslist. It will be long enough anyway.

    _dispatchedCond.notify_one();
}

void FastOS_ThreadInterface::SetBreakFlag()
{
    std::lock_guard<std::mutex> dispatchedGuard(_dispatchedMutex);
    _breakFlag.store(true, std::memory_order_relaxed);
    _dispatchedCond.notify_one();
}


FastOS_ThreadInterface *FastOS_ThreadInterface::CreateThread(FastOS_ThreadPool *pool)
{
    FastOS_ThreadInterface *thread = new FastOS_Thread(pool);

    if(!thread->Initialize()) {
        delete(thread);
        thread = nullptr;
    }

    return thread;
}

void FastOS_ThreadInterface::Join ()
{
    std::unique_lock<std::mutex> runningGuard(_runningMutex);
    while (_runningFlag) {
        _runningCond.wait(runningGuard);
    }
}


// ----------------------------------------------------------------------
// FastOS_Runnable
// ----------------------------------------------------------------------

FastOS_Runnable::FastOS_Runnable()
    : _thread(nullptr)
{
}

FastOS_Runnable::~FastOS_Runnable()
{
    //      assert(_thread == nullptr);
}