bthread.cpp 13.2 KB
Newer Older
gejun's avatar
gejun committed
1
// bthread - A M:N threading library to make applications more concurrent.
gejun's avatar
gejun committed
2
// Copyright (c) 2012 Baidu, Inc.
gejun's avatar
gejun committed
3 4 5 6 7 8 9 10 11 12 13 14
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
gejun's avatar
gejun committed
15 16 17 18 19

// Author: Ge,Jun (gejun@baidu.com)
// Date: Tue Jul 10 17:40:58 CST 2012

#include <gflags/gflags.h>
20 21
#include "butil/macros.h"                       // BAIDU_CASSERT
#include "butil/logging.h"
gejun's avatar
gejun committed
22 23 24 25 26 27 28 29 30 31
#include "bthread/task_group.h"                // TaskGroup
#include "bthread/task_control.h"              // TaskControl
#include "bthread/timer_thread.h"
#include "bthread/list_of_abafree_id.h"
#include "bthread/bthread.h"

namespace bthread {

DEFINE_int32(bthread_concurrency, 8 + BTHREAD_EPOLL_THREAD_NUM,
             "Number of pthread workers");
32 33 34 35 36 37

DEFINE_int32(bthread_min_concurrency, 0,
            "Initial number of pthread workers which will be added on-demand."
            " The laziness is disabled when this value is non-positive,"
            " and workers will be created eagerly according to -bthread_concurrency and bthread_setconcurrency(). ");

gejun's avatar
gejun committed
38 39 40 41 42 43 44 45
static bool never_set_bthread_concurrency = true;

static bool validate_bthread_concurrency(const char*, int32_t val) {
    // bthread_setconcurrency sets the flag on success path which should
    // not be strictly in a validator. But it's OK for a int flag.
    return bthread_setconcurrency(val) == 0;
}
const int ALLOW_UNUSED register_FLAGS_bthread_concurrency = 
46
    ::GFLAGS_NS::RegisterFlagValidator(&FLAGS_bthread_concurrency,
gejun's avatar
gejun committed
47 48
                                    validate_bthread_concurrency);

49 50 51
static bool validate_bthread_min_concurrency(const char*, int32_t val);

const int ALLOW_UNUSED register_FLAGS_bthread_min_concurrency =
52
    ::GFLAGS_NS::RegisterFlagValidator(&FLAGS_bthread_min_concurrency,
53 54
                                    validate_bthread_min_concurrency);

55
BAIDU_CASSERT(sizeof(TaskControl*) == sizeof(butil::atomic<TaskControl*>), atomic_size_match);
gejun's avatar
gejun committed
56 57 58 59

pthread_mutex_t g_task_control_mutex = PTHREAD_MUTEX_INITIALIZER;
// Referenced in rpc, needs to be extern.
// Notice that we can't declare the variable as atomic<TaskControl*> which
60
// are not constructed before main().
gejun's avatar
gejun committed
61 62 63 64 65 66 67 68 69 70
TaskControl* g_task_control = NULL;

extern BAIDU_THREAD_LOCAL TaskGroup* tls_task_group;
extern void (*g_worker_startfn)();

inline TaskControl* get_task_control() {
    return g_task_control;
}

inline TaskControl* get_or_new_task_control() {
71 72
    butil::atomic<TaskControl*>* p = (butil::atomic<TaskControl*>*)&g_task_control;
    TaskControl* c = p->load(butil::memory_order_consume);
gejun's avatar
gejun committed
73 74 75 76
    if (c != NULL) {
        return c;
    }
    BAIDU_SCOPED_LOCK(g_task_control_mutex);
77
    c = p->load(butil::memory_order_consume);
gejun's avatar
gejun committed
78 79 80 81 82 83 84
    if (c != NULL) {
        return c;
    }
    c = new (std::nothrow) TaskControl;
    if (NULL == c) {
        return NULL;
    }
85 86 87 88
    int concurrency = FLAGS_bthread_min_concurrency > 0 ?
        FLAGS_bthread_min_concurrency :
        FLAGS_bthread_concurrency;
    if (c->init(concurrency) != 0) {
gejun's avatar
gejun committed
89 90 91 92
        LOG(ERROR) << "Fail to init g_task_control";
        delete c;
        return NULL;
    }
93
    p->store(c, butil::memory_order_release);
gejun's avatar
gejun committed
94 95 96
    return c;
}

97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
static bool validate_bthread_min_concurrency(const char*, int32_t val) {
    if (val <= 0) {
        return true;
    }
    if (val < BTHREAD_MIN_CONCURRENCY || val > FLAGS_bthread_concurrency) {
        return false;
    }
    TaskControl* c = get_task_control();
    if (!c) {
        return true;
    }
    BAIDU_SCOPED_LOCK(g_task_control_mutex);
    int concurrency = c->concurrency();
    if (val > concurrency) {
        int added = c->add_workers(val - concurrency);
        return added == (val - concurrency);
    } else {
        return true;
    }
}

gejun's avatar
gejun committed
118 119
__thread TaskGroup* tls_task_group_nosignal = NULL;

120
BUTIL_FORCE_INLINE int
121 122 123 124
start_from_non_worker(bthread_t* __restrict tid,
                      const bthread_attr_t* __restrict attr,
                      void * (*fn)(void*),
                      void* __restrict arg) {
gejun's avatar
gejun committed
125 126 127 128 129 130 131 132 133 134 135 136 137 138
    TaskControl* c = get_or_new_task_control();
    if (NULL == c) {
        return ENOMEM;
    }
    if (attr != NULL && (attr->flags & BTHREAD_NOSIGNAL)) {
        // Remember the TaskGroup to insert NOSIGNAL tasks for 2 reasons:
        // 1. NOSIGNAL is often for creating many bthreads in batch,
        //    inserting into the same TaskGroup maximizes the batch.
        // 2. bthread_flush() needs to know which TaskGroup to flush.
        TaskGroup* g = tls_task_group_nosignal;
        if (NULL == g) {
            g = c->choose_one_group();
            tls_task_group_nosignal = g;
        }
139
        return g->start_background<true>(tid, attr, fn, arg);
gejun's avatar
gejun committed
140
    }
141 142
    return c->choose_one_group()->start_background<true>(
        tid, attr, fn, arg);
gejun's avatar
gejun committed
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
}

struct TidTraits {
    static const size_t BLOCK_SIZE = 63;
    static const size_t MAX_ENTRIES = 65536;
    static const bthread_t ID_INIT;
    static bool exists(bthread_t id) { return bthread::TaskGroup::exists(id); }
};
const bthread_t TidTraits::ID_INIT = INVALID_BTHREAD;

typedef ListOfABAFreeId<bthread_t, TidTraits> TidList;

struct TidStopper {
    void operator()(bthread_t id) const { bthread_stop(id); }
};
struct TidJoiner {
    void operator()(bthread_t & id) const {
        bthread_join(id, NULL);
        id = INVALID_BTHREAD;
    }
};

}  // namespace bthread

extern "C" {

int bthread_start_urgent(bthread_t* __restrict tid,
                         const bthread_attr_t* __restrict attr,
                         void * (*fn)(void*),
gejun's avatar
gejun committed
172
                         void* __restrict arg) {
gejun's avatar
gejun committed
173 174 175 176 177 178 179 180 181 182 183
    bthread::TaskGroup* g = bthread::tls_task_group;
    if (g) {
        // start from worker
        return bthread::TaskGroup::start_foreground(&g, tid, attr, fn, arg);
    }
    return bthread::start_from_non_worker(tid, attr, fn, arg);
}

int bthread_start_background(bthread_t* __restrict tid,
                             const bthread_attr_t* __restrict attr,
                             void * (*fn)(void*),
gejun's avatar
gejun committed
184
                             void* __restrict arg) {
gejun's avatar
gejun committed
185 186 187
    bthread::TaskGroup* g = bthread::tls_task_group;
    if (g) {
        // start from worker
188
        return g->start_background<false>(tid, attr, fn, arg);
gejun's avatar
gejun committed
189 190 191 192
    }
    return bthread::start_from_non_worker(tid, attr, fn, arg);
}

gejun's avatar
gejun committed
193
void bthread_flush() {
gejun's avatar
gejun committed
194 195
    bthread::TaskGroup* g = bthread::tls_task_group;
    if (g) {
196
        return g->flush_nosignal_tasks();
gejun's avatar
gejun committed
197 198 199 200 201
    }
    g = bthread::tls_task_group_nosignal;
    if (g) {
        // NOSIGNAL tasks were created in this non-worker.
        bthread::tls_task_group_nosignal = NULL;
202
        return g->flush_nosignal_tasks_remote();
gejun's avatar
gejun committed
203 204 205
    }
}

gejun's avatar
gejun committed
206
int bthread_interrupt(bthread_t tid) {
207 208 209
    return bthread::TaskGroup::interrupt(tid, bthread::get_task_control());
}

gejun's avatar
gejun committed
210
int bthread_stop(bthread_t tid) {
211 212
    bthread::TaskGroup::set_stopped(tid);
    return bthread_interrupt(tid);
gejun's avatar
gejun committed
213 214
}

gejun's avatar
gejun committed
215
int bthread_stopped(bthread_t tid) {
216
    return (int)bthread::TaskGroup::is_stopped(tid);
gejun's avatar
gejun committed
217 218
}

gejun's avatar
gejun committed
219
bthread_t bthread_self(void) {
gejun's avatar
gejun committed
220 221 222 223 224 225 226
    bthread::TaskGroup* g = bthread::tls_task_group;
    // note: return 0 for main tasks now, which include main thread and
    // all work threads. So that we can identify main tasks from logs
    // more easily. This is probably questionable in future.
    if (g != NULL && !g->is_current_main_task()/*note*/) {
        return g->current_tid();
    }
227
    return INVALID_BTHREAD;
gejun's avatar
gejun committed
228 229
}

gejun's avatar
gejun committed
230
int bthread_equal(bthread_t t1, bthread_t t2) {
gejun's avatar
gejun committed
231 232 233 234 235 236 237 238 239 240 241 242
    return t1 == t2;
}

void bthread_exit(void* retval) {
    bthread::TaskGroup* g = bthread::tls_task_group;
    if (g != NULL && !g->is_current_main_task()) {
        throw bthread::ExitException(retval);
    } else {
        pthread_exit(retval);
    }
}

gejun's avatar
gejun committed
243
int bthread_join(bthread_t tid, void** thread_return) {
gejun's avatar
gejun committed
244 245 246
    return bthread::TaskGroup::join(tid, thread_return);
}

gejun's avatar
gejun committed
247
int bthread_attr_init(bthread_attr_t* a) {
gejun's avatar
gejun committed
248 249 250 251
    *a = BTHREAD_ATTR_NORMAL;
    return 0;
}

gejun's avatar
gejun committed
252
int bthread_attr_destroy(bthread_attr_t*) {
gejun's avatar
gejun committed
253 254 255
    return 0;
}

gejun's avatar
gejun committed
256
int bthread_getattr(bthread_t tid, bthread_attr_t* attr) {
gejun's avatar
gejun committed
257 258 259
    return bthread::TaskGroup::get_attr(tid, attr);
}

gejun's avatar
gejun committed
260
int bthread_getconcurrency(void) {
gejun's avatar
gejun committed
261 262 263
    return bthread::FLAGS_bthread_concurrency;
}

gejun's avatar
gejun committed
264
int bthread_setconcurrency(int num) {
gejun's avatar
gejun committed
265 266 267 268
    if (num < BTHREAD_MIN_CONCURRENCY || num > BTHREAD_MAX_CONCURRENCY) {
        LOG(ERROR) << "Invalid concurrency=" << num;
        return EINVAL;
    }
269 270 271 272 273 274 275 276 277 278
    if (bthread::FLAGS_bthread_min_concurrency > 0) {
        if (num < bthread::FLAGS_bthread_min_concurrency) {
            return EINVAL;
        }
        if (bthread::never_set_bthread_concurrency) {
            bthread::never_set_bthread_concurrency = false;
        }
        bthread::FLAGS_bthread_concurrency = num;
        return 0;
    }
gejun's avatar
gejun committed
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
    bthread::TaskControl* c = bthread::get_task_control();
    if (c != NULL) {
        if (num < c->concurrency()) {
            return EPERM;
        } else if (num == c->concurrency()) {
            return 0;
        }
    }
    BAIDU_SCOPED_LOCK(bthread::g_task_control_mutex);
    c = bthread::get_task_control();
    if (c == NULL) {
        if (bthread::never_set_bthread_concurrency) {
            bthread::never_set_bthread_concurrency = false;
            bthread::FLAGS_bthread_concurrency = num;
        } else if (num > bthread::FLAGS_bthread_concurrency) {
            bthread::FLAGS_bthread_concurrency = num;
        }
        return 0;
    }
    if (bthread::FLAGS_bthread_concurrency != c->concurrency()) {
        LOG(ERROR) << "CHECK failed: bthread_concurrency="
                   << bthread::FLAGS_bthread_concurrency
                   << " != tc_concurrency=" << c->concurrency();
        bthread::FLAGS_bthread_concurrency = c->concurrency();
    }
    if (num > bthread::FLAGS_bthread_concurrency) {
        // Create more workers if needed.
        bthread::FLAGS_bthread_concurrency +=
            c->add_workers(num - bthread::FLAGS_bthread_concurrency);
        return 0;
    }
    return (num == bthread::FLAGS_bthread_concurrency ? 0 : EPERM);
}

gejun's avatar
gejun committed
313
int bthread_about_to_quit() {
gejun's avatar
gejun committed
314 315 316 317 318 319 320 321 322
    bthread::TaskGroup* g = bthread::tls_task_group;
    if (g != NULL) {
        g->current_task()->about_to_quit = true;
        return 0;
    }
    return EPERM;
}

int bthread_timer_add(bthread_timer_t* id, timespec abstime,
gejun's avatar
gejun committed
323
                      void (*on_timer)(void*), void* arg) {
gejun's avatar
gejun committed
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
    bthread::TaskControl* c = bthread::get_or_new_task_control();
    if (c == NULL) {
        return ENOMEM;
    }
    bthread::TimerThread* tt = bthread::get_or_create_global_timer_thread();
    if (tt == NULL) {
        return ENOMEM;
    }
    bthread_timer_t tmp = tt->schedule(on_timer, arg, abstime);
    if (tmp != 0) {
        *id = tmp;
        return 0;
    }
    return ESTOP;
}

gejun's avatar
gejun committed
340
int bthread_timer_del(bthread_timer_t id) {
gejun's avatar
gejun committed
341 342 343 344 345 346 347 348 349 350 351 352 353 354
    bthread::TaskControl* c = bthread::get_task_control();
    if (c != NULL) {
        bthread::TimerThread* tt = bthread::get_global_timer_thread();
        if (tt == NULL) {
            return EINVAL;
        }
        const int state = tt->unschedule(id);
        if (state >= 0) {
            return state;
        }
    }
    return EINVAL;
}

gejun's avatar
gejun committed
355
int bthread_usleep(uint64_t microseconds) {
gejun's avatar
gejun committed
356 357 358 359 360 361 362
    bthread::TaskGroup* g = bthread::tls_task_group;
    if (NULL != g && !g->is_current_pthread_task()) {
        return bthread::TaskGroup::usleep(&g, microseconds);
    }
    return ::usleep(microseconds);
}

gejun's avatar
gejun committed
363
int bthread_yield(void) {
gejun's avatar
gejun committed
364 365
    bthread::TaskGroup* g = bthread::tls_task_group;
    if (NULL != g && !g->is_current_pthread_task()) {
366 367
        bthread::TaskGroup::yield(&g);
        return 0;
gejun's avatar
gejun committed
368
    }
gejun's avatar
gejun committed
369 370
    // pthread_yield is not available on MAC
    return sched_yield();
gejun's avatar
gejun committed
371 372
}

gejun's avatar
gejun committed
373
int bthread_set_worker_startfn(void (*start_fn)()) {
gejun's avatar
gejun committed
374 375 376 377 378 379 380
    if (start_fn == NULL) {
        return EINVAL;
    }
    bthread::g_worker_startfn = start_fn;
    return 0;
}

gejun's avatar
gejun committed
381
void bthread_stop_world() {
gejun's avatar
gejun committed
382 383 384 385 386 387 388 389
    bthread::TaskControl* c = bthread::get_task_control();
    if (c != NULL) {
        c->stop_and_join();
    }
}

int bthread_list_init(bthread_list_t* list,
                      unsigned /*size*/,
gejun's avatar
gejun committed
390
                      unsigned /*conflict_size*/) {
gejun's avatar
gejun committed
391 392 393 394 395 396 397 398 399 400 401 402
    list->impl = new (std::nothrow) bthread::TidList;
    if (NULL == list->impl) {
        return ENOMEM;
    }
    // Set unused fields to zero as well.
    list->head = 0;
    list->size = 0;
    list->conflict_head = 0;
    list->conflict_size = 0;
    return 0;
}

gejun's avatar
gejun committed
403
void bthread_list_destroy(bthread_list_t* list) {
gejun's avatar
gejun committed
404 405 406 407
    delete static_cast<bthread::TidList*>(list->impl);
    list->impl = NULL;
}

gejun's avatar
gejun committed
408
int bthread_list_add(bthread_list_t* list, bthread_t id) {
gejun's avatar
gejun committed
409 410 411 412 413 414
    if (list->impl == NULL) {
        return EINVAL;
    }
    return static_cast<bthread::TidList*>(list->impl)->add(id);
}

gejun's avatar
gejun committed
415
int bthread_list_stop(bthread_list_t* list) {
gejun's avatar
gejun committed
416 417 418 419 420 421 422
    if (list->impl == NULL) {
        return EINVAL;
    }
    static_cast<bthread::TidList*>(list->impl)->apply(bthread::TidStopper());
    return 0;
}

gejun's avatar
gejun committed
423
int bthread_list_join(bthread_list_t* list) {
gejun's avatar
gejun committed
424 425 426 427 428 429 430 431
    if (list->impl == NULL) {
        return EINVAL;
    }
    static_cast<bthread::TidList*>(list->impl)->apply(bthread::TidJoiner());
    return 0;
}
    
}  // extern "C"