diff --git a/src/bthread/bthread.cpp b/src/bthread/bthread.cpp index 7eb6810dce..727b4ebace 100644 --- a/src/bthread/bthread.cpp +++ b/src/bthread/bthread.cpp @@ -84,7 +84,7 @@ 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 which // are not constructed before main(). -TaskControl* g_task_control = NULL; +TaskControl* g_task_control = nullptr; EXTERN_BAIDU_VOLATILE_THREAD_LOCAL(TaskGroup*, tls_task_group); extern void (*g_worker_startfn)(); @@ -97,40 +97,37 @@ inline TaskControl* get_task_control() { inline TaskControl* get_or_new_task_control() { butil::atomic* p = (butil::atomic*)&g_task_control; TaskControl* c = p->load(butil::memory_order_consume); - if (c != NULL) { + if (c != nullptr) { return c; } BAIDU_SCOPED_LOCK(g_task_control_mutex); c = p->load(butil::memory_order_consume); - if (c != NULL) { + if (c != nullptr) { return c; } - c = new (std::nothrow) TaskControl; - if (NULL == c) { - return NULL; - } + c = new TaskControl; int concurrency = FLAGS_bthread_min_concurrency > 0 ? FLAGS_bthread_min_concurrency : FLAGS_bthread_concurrency; if (c->init(concurrency) != 0) { LOG(ERROR) << "Fail to init g_task_control"; delete c; - return NULL; + return nullptr; } p->store(c, butil::memory_order_release); return c; } #ifdef BRPC_BTHREAD_TRACER -BAIDU_THREAD_LOCAL TaskMeta* pthread_fake_meta = NULL; +BAIDU_THREAD_LOCAL TaskMeta* pthread_fake_meta = nullptr; bthread_t init_for_pthread_stack_trace() { - if (NULL != pthread_fake_meta) { + if (nullptr != pthread_fake_meta) { return pthread_fake_meta->tid; } TaskControl* c = get_task_control(); - if (NULL == c) { + if (nullptr == c) { LOG(ERROR) << "TaskControl has not been created, " "please use bthread_start_xxx before call this function"; return INVALID_BTHREAD; @@ -138,7 +135,7 @@ bthread_t init_for_pthread_stack_trace() { butil::ResourceId slot; pthread_fake_meta = butil::get_resource(&slot); - if (BAIDU_UNLIKELY(NULL == pthread_fake_meta)) { + if (BAIDU_UNLIKELY(nullptr == pthread_fake_meta)) { LOG(ERROR) << "Fail to get TaskMeta"; return INVALID_BTHREAD; } @@ -170,7 +167,7 @@ bthread_t init_for_pthread_stack_trace() { TASK_STATUS_UNKNOWN, pthread_fake_meta); butil::return_resource(get_slot(pthread_fake_meta->tid)); - pthread_fake_meta = NULL; + pthread_fake_meta = nullptr; }); return pthread_fake_meta->tid; @@ -178,7 +175,7 @@ bthread_t init_for_pthread_stack_trace() { void stack_trace(std::ostream& os, bthread_t tid) { TaskControl* c = get_task_control(); - if (NULL == c) { + if (nullptr == c) { os << "TaskControl has not been created"; return; } @@ -187,7 +184,7 @@ void stack_trace(std::ostream& os, bthread_t tid) { std::string stack_trace(bthread_t tid) { TaskControl* c = get_task_control(); - if (NULL == c) { + if (nullptr == c) { return "TaskControl has not been created"; } return c->stack_trace(tid); @@ -198,7 +195,7 @@ std::string stack_trace(bthread_t tid) { // Print all living (started and not finished) bthreads void print_living_tasks(std::ostream& os, bool enable_trace) { TaskControl* c = get_task_control(); - if (NULL == c) { + if (nullptr == c) { os << "TaskControl has not been created"; return; } @@ -250,7 +247,7 @@ static bool validate_bthread_current_tag(const char*, int32_t val) { } BAIDU_SCOPED_LOCK(bthread::g_task_control_mutex); auto c = get_task_control(); - if (c == NULL) { + if (c == nullptr) { FLAGS_bthread_concurrency_by_tag = 8 + BTHREAD_EPOLL_THREAD_NUM; return true; } @@ -262,7 +259,7 @@ static bool validate_bthread_concurrency_by_tag(const char*, int32_t val) { return bthread_setconcurrency_by_tag(val, FLAGS_bthread_current_tag) == 0; } -BAIDU_VOLATILE_THREAD_LOCAL(TaskGroup*, tls_task_group_nosignal, NULL); +BAIDU_VOLATILE_THREAD_LOCAL(TaskGroup*, tls_task_group_nosignal, nullptr); BUTIL_FORCE_INLINE int start_from_non_worker(bthread_t* __restrict tid, @@ -270,20 +267,20 @@ start_from_non_worker(bthread_t* __restrict tid, void* (*fn)(void*), void* __restrict arg) { TaskControl* c = get_or_new_task_control(); - if (NULL == c) { + if (nullptr == c) { return ENOMEM; } bthread_tag_t tag = BTHREAD_TAG_DEFAULT; - if (attr != NULL && attr->tag != BTHREAD_TAG_INVALID) { + if (attr != nullptr && attr->tag != BTHREAD_TAG_INVALID) { tag = attr->tag; } - if (attr != NULL && (attr->flags & BTHREAD_NOSIGNAL)) { + if (attr != nullptr && (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. auto g = BAIDU_GET_VOLATILE_THREAD_LOCAL(tls_task_group_nosignal); - if (NULL == g) { + if (nullptr == g) { g = c->choose_one_group(tag); BAIDU_SET_VOLATILE_THREAD_LOCAL(tls_task_group_nosignal, g); } else { @@ -326,7 +323,7 @@ struct TidStopper { }; struct TidJoiner { void operator()(bthread_t & id) const { - bthread_join(id, NULL); + bthread_join(id, nullptr); id = INVALID_BTHREAD; } }; @@ -371,7 +368,7 @@ void bthread_flush() { g = bthread::BAIDU_GET_VOLATILE_THREAD_LOCAL(tls_task_group_nosignal); if (g) { // NOSIGNAL tasks were created in this non-worker. - bthread::BAIDU_SET_VOLATILE_THREAD_LOCAL(tls_task_group_nosignal, NULL); + bthread::BAIDU_SET_VOLATILE_THREAD_LOCAL(tls_task_group_nosignal, nullptr); return g->flush_nosignal_tasks_remote(); } } @@ -394,7 +391,7 @@ bthread_t bthread_self(void) { // 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 the future. - if (g != NULL && !g->is_current_main_task()/*note*/) { + if (g != nullptr && !g->is_current_main_task()/*note*/) { return g->current_tid(); } return INVALID_BTHREAD; @@ -406,7 +403,7 @@ int bthread_equal(bthread_t t1, bthread_t t2) { void bthread_exit(void* retval) { bthread::TaskGroup* g = bthread::BAIDU_GET_VOLATILE_THREAD_LOCAL(tls_task_group); - if (g != NULL && !g->is_current_main_task()) { + if (g != nullptr && !g->is_current_main_task()) { throw bthread::ExitException(retval); } else { pthread_exit(retval); @@ -450,7 +447,7 @@ int bthread_setconcurrency(int num) { return 0; } bthread::TaskControl* c = bthread::get_task_control(); - if (c != NULL) { + if (c != nullptr) { if (num < c->concurrency()) { return EPERM; } else if (num == c->concurrency()) { @@ -459,7 +456,7 @@ int bthread_setconcurrency(int num) { } BAIDU_SCOPED_LOCK(bthread::g_task_control_mutex); c = bthread::get_task_control(); - if (c == NULL) { + if (c == nullptr) { if (bthread::never_set_bthread_concurrency) { bthread::never_set_bthread_concurrency = false; bthread::FLAGS_bthread_concurrency = num; @@ -485,7 +482,7 @@ int bthread_setconcurrency(int num) { int bthread_getconcurrency_by_tag(bthread_tag_t tag) { BAIDU_SCOPED_LOCK(bthread::g_task_control_mutex); auto c = bthread::get_task_control(); - if (c == NULL) { + if (c == nullptr) { return EPERM; } return c->concurrency(tag); @@ -520,7 +517,7 @@ int bthread_setconcurrency_by_tag(int num, bthread_tag_t tag) { int bthread_about_to_quit() { bthread::TaskGroup* g = bthread::BAIDU_GET_VOLATILE_THREAD_LOCAL(tls_task_group); - if (g != NULL) { + if (g != nullptr) { bthread::TaskMeta* current_task = g->current_task(); if(!(current_task->attr.flags & BTHREAD_NEVER_QUIT)) { current_task->about_to_quit = true; @@ -533,11 +530,11 @@ int bthread_about_to_quit() { int bthread_timer_add(bthread_timer_t* id, timespec abstime, void (*on_timer)(void*), void* arg) { bthread::TaskControl* c = bthread::get_or_new_task_control(); - if (c == NULL) { + if (c == nullptr) { return ENOMEM; } bthread::TimerThread* tt = bthread::get_or_create_global_timer_thread(); - if (tt == NULL) { + if (tt == nullptr) { return ENOMEM; } bthread_timer_t tmp = tt->schedule(on_timer, arg, abstime); @@ -550,9 +547,9 @@ int bthread_timer_add(bthread_timer_t* id, timespec abstime, int bthread_timer_del(bthread_timer_t id) { bthread::TaskControl* c = bthread::get_task_control(); - if (c != NULL) { + if (c != nullptr) { bthread::TimerThread* tt = bthread::get_global_timer_thread(); - if (tt == NULL) { + if (tt == nullptr) { return EINVAL; } const int state = tt->unschedule(id); @@ -565,7 +562,7 @@ int bthread_timer_del(bthread_timer_t id) { int bthread_usleep(uint64_t microseconds) { bthread::TaskGroup* g = bthread::BAIDU_GET_VOLATILE_THREAD_LOCAL(tls_task_group); - if (NULL != g && !g->is_current_pthread_task()) { + if (nullptr != g && !g->is_current_pthread_task()) { return bthread::TaskGroup::usleep(&g, microseconds); } return ::usleep(microseconds); @@ -573,7 +570,7 @@ int bthread_usleep(uint64_t microseconds) { int bthread_yield(void) { bthread::TaskGroup* g = bthread::BAIDU_GET_VOLATILE_THREAD_LOCAL(tls_task_group); - if (NULL != g && !g->is_current_pthread_task()) { + if (nullptr != g && !g->is_current_pthread_task()) { bthread::TaskGroup::yield(&g); return 0; } @@ -582,7 +579,7 @@ int bthread_yield(void) { } int bthread_set_worker_startfn(void (*start_fn)()) { - if (start_fn == NULL) { + if (start_fn == nullptr) { return EINVAL; } bthread::g_worker_startfn = start_fn; @@ -590,7 +587,7 @@ int bthread_set_worker_startfn(void (*start_fn)()) { } int bthread_set_tagged_worker_startfn(void (*start_fn)(bthread_tag_t)) { - if (start_fn == NULL) { + if (start_fn == nullptr) { return EINVAL; } bthread::g_tagged_worker_startfn = start_fn; @@ -599,7 +596,7 @@ int bthread_set_tagged_worker_startfn(void (*start_fn)(bthread_tag_t)) { void bthread_stop_world() { bthread::TaskControl* c = bthread::get_task_control(); - if (c != NULL) { + if (c != nullptr) { c->stop_and_join(); } } @@ -607,10 +604,7 @@ void bthread_stop_world() { int bthread_list_init(bthread_list_t* list, unsigned /*size*/, unsigned /*conflict_size*/) { - list->impl = new (std::nothrow) bthread::TidList; - if (NULL == list->impl) { - return ENOMEM; - } + list->impl = new bthread::TidList; // Set unused fields to zero as well. list->head = 0; list->size = 0; @@ -621,18 +615,18 @@ int bthread_list_init(bthread_list_t* list, void bthread_list_destroy(bthread_list_t* list) { delete static_cast(list->impl); - list->impl = NULL; + list->impl = nullptr; } int bthread_list_add(bthread_list_t* list, bthread_t id) { - if (list->impl == NULL) { + if (list->impl == nullptr) { return EINVAL; } return static_cast(list->impl)->add(id); } int bthread_list_stop(bthread_list_t* list) { - if (list->impl == NULL) { + if (list->impl == nullptr) { return EINVAL; } static_cast(list->impl)->apply(bthread::TidStopper()); @@ -640,7 +634,7 @@ int bthread_list_stop(bthread_list_t* list) { } int bthread_list_join(bthread_list_t* list) { - if (list->impl == NULL) { + if (list->impl == nullptr) { return EINVAL; } static_cast(list->impl)->apply(bthread::TidJoiner()); @@ -649,12 +643,12 @@ int bthread_list_join(bthread_list_t* list) { bthread_tag_t bthread_self_tag(void) { bthread::TaskGroup* g = bthread::BAIDU_GET_VOLATILE_THREAD_LOCAL(tls_task_group); - return g != NULL ? g->tag() : BTHREAD_TAG_DEFAULT; + return g != nullptr ? g->tag() : BTHREAD_TAG_DEFAULT; } uint64_t bthread_cpu_clock_ns(void) { bthread::TaskGroup* g = bthread::BAIDU_GET_VOLATILE_THREAD_LOCAL(tls_task_group); - if (g != NULL && !g->is_current_main_task()) { + if (g != nullptr && !g->is_current_main_task()) { return g->current_task_cpu_clock_ns(); } return 0; diff --git a/src/bthread/bthread.h b/src/bthread/bthread.h index 402fe70cfe..008beffadc 100644 --- a/src/bthread/bthread.h +++ b/src/bthread/bthread.h @@ -180,9 +180,9 @@ extern int bthread_usleep(uint64_t microseconds); // --------------------------------------------- // Initialize `mutex' using attributes in `mutex_attr', or use the -// default values if later is NULL. +// default values if later is nullptr. // NOTE: mutexattr is not used in current mutex implementation. User shall -// always pass a NULL attribute. +// always pass a nullptr attribute. extern int bthread_mutex_init(bthread_mutex_t* __restrict mutex, const bthread_mutexattr_t* __restrict attr); @@ -214,9 +214,9 @@ extern int bthread_mutexattr_destroy(bthread_mutexattr_t* attr); // ----------------------------------------------- // Initialize condition variable `cond' using attributes `cond_attr', or use -// the default values if later is NULL. +// the default values if later is nullptr. // NOTE: cond_attr is not used in current condition implementation. User shall -// always pass a NULL attribute. +// always pass a nullptr attribute. extern int bthread_cond_init(bthread_cond_t* __restrict cond, const bthread_condattr_t* __restrict cond_attr); @@ -248,7 +248,7 @@ extern int bthread_cond_timedwait( // ------------------------------------------- // Initialize read-write lock `rwlock' using attributes `attr', or use -// the default values if later is NULL. +// the default values if later is nullptr. extern int bthread_rwlock_init(bthread_rwlock_t* __restrict rwlock, const bthread_rwlockattr_t* __restrict attr); @@ -364,9 +364,9 @@ extern int bthread_barrier_wait(bthread_barrier_t* barrier); // Create a key value identifying a slot in a thread-specific data area. // Each thread maintains a distinct thread-specific data area. -// `destructor', if non-NULL, is called with the value associated to that key +// `destructor', if non-nullptr, is called with the value associated to that key // when the key is destroyed. `destructor' is not called if the value -// associated is NULL when the key is destroyed. +// associated is nullptr when the key is destroyed. // Returns 0 on success, error code otherwise. extern int bthread_key_create(bthread_key_t* key, void (*destructor)(void* data)); @@ -395,8 +395,8 @@ extern int bthread_key_delete(bthread_key_t key); extern int bthread_setspecific(bthread_key_t key, void* data); // Return current value of the thread-specific slot identified by `key'. -// If bthread_setspecific() had not been called in the thread, return NULL. -// If the key is invalid or deleted, return NULL. +// If bthread_setspecific() had not been called in the thread, return nullptr. +// If the key is invalid or deleted, return nullptr. extern void* bthread_getspecific(bthread_key_t key); // Return current bthread tag @@ -442,12 +442,12 @@ typedef void (*bthread_end_span_fn)(void); // Parameters: // create_fn - Called when creating a bthread with BTHREAD_INHERIT_SPAN flag. // Should return a heap-allocated span context (e.g., weak_ptr*). -// Returns NULL if span creation is disabled or fails. +// Returns nullptr if span creation is disabled or fails. // destroy_fn - Called to destroy the span context when bthread exits or cleans up. // Receives the pointer returned by create_fn. // end_fn - Called when bthread ends to finalize the span (e.g., set end time). // -// All three callbacks must be provided together, or all NULL to disable span tracking. +// All three callbacks must be provided together, or all nullptr to disable span tracking. // This function should only be called once during initialization. // // Returns: diff --git a/src/bthread/bthread_once.cpp b/src/bthread/bthread_once.cpp index a5751bc7ee..be61f51468 100644 --- a/src/bthread/bthread_once.cpp +++ b/src/bthread/bthread_once.cpp @@ -63,7 +63,7 @@ int bthread_once_impl(bthread_once_t* once_control, void (*init_routine)()) { } // Unless your constructor can be very time consuming, it is very unlikely o hit // this race. When it does, we just wait the thread until the object has been created. - if (bthread::butex_wait(butex, val, NULL) < 0 && + if (bthread::butex_wait(butex, val, nullptr) < 0 && errno != EWOULDBLOCK && errno != EINTR/*note*/) { return errno; } diff --git a/src/bthread/butex.cpp b/src/bthread/butex.cpp index d833465c57..63920ca9eb 100644 --- a/src/bthread/butex.cpp +++ b/src/bthread/butex.cpp @@ -145,18 +145,18 @@ static void wakeup_pthread(ButexPthreadWaiter* pw) { bool erase_from_butex(ButexWaiter*, bool, WaiterState); int wait_pthread(ButexPthreadWaiter& pw, const timespec* abstime) { - timespec* ptimeout = NULL; + timespec* ptimeout = nullptr; timespec timeout; int64_t timeout_us = 0; int rc; while (true) { - if (abstime != NULL) { + if (abstime != nullptr) { timeout_us = butil::timespec_to_microseconds(*abstime) - butil::gettimeofday_us(); timeout = butil::microseconds_to_timespec(timeout_us); ptimeout = &timeout; } - if (timeout_us > MIN_SLEEP_US || abstime == NULL) { + if (timeout_us > MIN_SLEEP_US || abstime == nullptr) { rc = futex_wait_private(&pw.sig, PTHREAD_NOT_SIGNALLED, ptimeout); if (PTHREAD_NOT_SIGNALLED != pw.sig.load(butil::memory_order_acquire)) { // If `sig' is changed, wakeup_pthread() must be called and `pw' @@ -177,8 +177,8 @@ int wait_pthread(ButexPthreadWaiter& pw, const timespec* abstime) { // Acquire fence makes this thread sees changes before wakeup. if (pw.sig.load(butil::memory_order_acquire) == PTHREAD_NOT_SIGNALLED) { // already timedout, abstime and ptimeout are expired. - abstime = NULL; - ptimeout = NULL; + abstime = nullptr; + ptimeout = nullptr; continue; } } @@ -266,7 +266,7 @@ void* butex_create() { if (b) { return &b->value; } - return NULL; + return nullptr; } void butex_destroy(void* butex) { @@ -305,7 +305,7 @@ inline void run_in_local_task_group(TaskGroup* g, TaskMeta* next_meta, bool nosi int butex_wake(void* arg, bool nosignal) { Butex* b = container_of(static_cast*>(arg), Butex, value); - ButexWaiter* front = NULL; + ButexWaiter* front = nullptr; { BAIDU_SCOPED_LOCK(b->waiter_lock); if (b->waiters.empty()) { @@ -313,7 +313,7 @@ int butex_wake(void* arg, bool nosignal) { } front = b->waiters.head()->value(); front->RemoveFromList(); - front->container.store(NULL, butil::memory_order_relaxed); + front->container.store(nullptr, butil::memory_order_relaxed); } if (front->tid == 0) { wakeup_pthread(static_cast(front)); @@ -340,7 +340,7 @@ int butex_wake_n(void* arg, size_t n, bool nosignal) { for (size_t i = 0; (n == 0 || i < n) && !b->waiters.empty(); ++i) { ButexWaiter* bw = b->waiters.head()->value(); bw->RemoveFromList(); - bw->container.store(NULL, butil::memory_order_relaxed); + bw->container.store(nullptr, butil::memory_order_relaxed); if (bw->tid) { bthread_waiters.Append(bw); } else { @@ -404,7 +404,7 @@ int butex_wake_except(void* arg, bthread_t excluded_bthread) { ButexWaiterList bthread_waiters; ButexWaiterList pthread_waiters; { - ButexWaiter* excluded_waiter = NULL; + ButexWaiter* excluded_waiter = nullptr; BAIDU_SCOPED_LOCK(b->waiter_lock); while (!b->waiters.empty()) { ButexWaiter* bw = b->waiters.head()->value(); @@ -413,12 +413,12 @@ int butex_wake_except(void* arg, bthread_t excluded_bthread) { if (bw->tid) { if (bw->tid != excluded_bthread) { bthread_waiters.Append(bw); - bw->container.store(NULL, butil::memory_order_relaxed); + bw->container.store(nullptr, butil::memory_order_relaxed); } else { excluded_waiter = bw; } } else { - bw->container.store(NULL, butil::memory_order_relaxed); + bw->container.store(nullptr, butil::memory_order_relaxed); pthread_waiters.Append(bw); } } @@ -463,7 +463,7 @@ int butex_requeue(void* arg, void* arg2) { Butex* b = container_of(static_cast*>(arg), Butex, value); Butex* m = container_of(static_cast*>(arg2), Butex, value); - ButexWaiter* front = NULL; + ButexWaiter* front = nullptr; { std::unique_lock lck1(b->waiter_lock, std::defer_lock); std::unique_lock lck2(m->waiter_lock, std::defer_lock); @@ -474,7 +474,7 @@ int butex_requeue(void* arg, void* arg2) { front = b->waiters.head()->value(); front->RemoveFromList(); - front->container.store(NULL, butil::memory_order_relaxed); + front->container.store(nullptr, butil::memory_order_relaxed); while (!b->waiters.empty()) { ButexWaiter* bw = b->waiters.head()->value(); @@ -492,7 +492,7 @@ int butex_requeue(void* arg, void* arg2) { unsleep_if_necessary(bbw, get_global_timer_thread()); auto g = is_same_tag(bbw->task_meta->attr.tag) ? BAIDU_GET_VOLATILE_THREAD_LOCAL(tls_task_group) - : NULL; + : nullptr; if (g) { TaskGroup::exchange(&g, bbw->task_meta); } else { @@ -515,16 +515,16 @@ bool erase_from_butex_because_of_interruption(ButexWaiter* bw) { inline bool erase_from_butex(ButexWaiter* bw, bool wakeup, WaiterState state) { // `bw' is guaranteed to be valid inside this function because waiter // will wait until this function being cancelled or finished. - // NOTE: This function must be no-op when bw->container is NULL. + // NOTE: This function must be no-op when bw->container is nullptr. bool erased = false; Butex* b; int saved_errno = errno; while ((b = bw->container.load(butil::memory_order_acquire))) { - // b can be NULL when the waiter is scheduled but queued. + // b can be nullptr when the waiter is scheduled but queued. BAIDU_SCOPED_LOCK(b->waiter_lock); if (b == bw->container.load(butil::memory_order_relaxed)) { bw->RemoveFromList(); - bw->container.store(NULL, butil::memory_order_relaxed); + bw->container.store(nullptr, butil::memory_order_relaxed); if (bw->tid) { static_cast(bw)->waiter_state = state; } @@ -584,7 +584,7 @@ void wait_for_butex(void* arg) { #ifdef BRPC_BTHREAD_TRACER bw->control->_task_tracer.set_status(TASK_STATUS_SUSPENDED, bw->task_meta); #endif // BRPC_BTHREAD_TRACER - if (bw->abstime != NULL) { + if (bw->abstime != nullptr) { bw->sleep_id = get_global_timer_thread()->schedule( erase_from_butex_and_wakeup, bw, *bw->abstime); if (!bw->sleep_id) { // TimerThread stopped. @@ -596,7 +596,7 @@ void wait_for_butex(void* arg) { } } - // b->container is NULL which makes erase_from_butex_and_wakeup() and + // b->container is nullptr which makes erase_from_butex_and_wakeup() and // TaskGroup::interrupt() no-op, there's no race between following code and // the two functions. The on-stack ButexBthreadWaiter is safe to use and // bw->waiter_state will not change again. @@ -616,7 +616,7 @@ void wait_for_butex(void* arg) { static int butex_wait_from_pthread(TaskGroup* g, Butex* b, int expected_value, const timespec* abstime, bool prepend) { - TaskMeta* task = NULL; + TaskMeta* task = nullptr; ButexPthreadWaiter pw; pw.tid = 0; pw.sig.store(PTHREAD_NOT_SIGNALLED, butil::memory_order_relaxed); @@ -631,7 +631,7 @@ static int butex_wait_from_pthread(TaskGroup* g, Butex* b, int expected_value, b->waiter_lock.unlock(); errno = EWOULDBLOCK; rc = -1; - } else if (task != NULL && task->interrupted) { + } else if (task != nullptr && task->interrupted) { b->waiter_lock.unlock(); // Race with set and may consume multiple interruptions, which are OK. task->interrupted = false; @@ -656,10 +656,10 @@ static int butex_wait_from_pthread(TaskGroup* g, Butex* b, int expected_value, #endif } if (task) { - // If current_waiter is NULL, TaskGroup::interrupt() is running and - // using pw, spin until current_waiter != NULL. + // If current_waiter is nullptr, TaskGroup::interrupt() is running and + // using pw, spin until current_waiter != nullptr. BT_LOOP_WHEN(task->current_waiter.exchange( - NULL, butil::memory_order_acquire) == NULL, + nullptr, butil::memory_order_acquire) == nullptr, 30/*nops before sched_yield*/); if (task->interrupted) { task->interrupted = false; @@ -682,13 +682,13 @@ int butex_wait(void* arg, int expected_value, const timespec* abstime, bool prep return -1; } TaskGroup* g = BAIDU_GET_VOLATILE_THREAD_LOCAL(tls_task_group); - if (NULL == g || g->is_current_pthread_task()) { + if (nullptr == g || g->is_current_pthread_task()) { return butex_wait_from_pthread(g, b, expected_value, abstime, prepend); } ButexBthreadWaiter bbw; // tid is 0 iff the thread is non-bthread bbw.tid = g->current_tid(); - bbw.container.store(NULL, butil::memory_order_relaxed); + bbw.container.store(nullptr, butil::memory_order_relaxed); bbw.task_meta = g->current_task(); bbw.sleep_id = 0; bbw.waiter_state = WAITER_STATE_READY; @@ -697,7 +697,7 @@ int butex_wait(void* arg, int expected_value, const timespec* abstime, bool prep bbw.control = g->control(); bbw.abstime = abstime; - if (abstime != NULL) { + if (abstime != nullptr) { // Schedule timer before queueing. If the timer is triggered before // queueing, cancel queueing. This is a kind of optimistic locking. if (butil::timespec_to_microseconds(*abstime) < @@ -724,10 +724,10 @@ int butex_wait(void* arg, int expected_value, const timespec* abstime, bool prep BT_LOOP_WHEN(unsleep_if_necessary(&bbw, get_global_timer_thread()) < 0, 30/*nops before sched_yield*/); - // If current_waiter is NULL, TaskGroup::interrupt() is running and using bbw. - // Spin until current_waiter != NULL. + // If current_waiter is nullptr, TaskGroup::interrupt() is running and using bbw. + // Spin until current_waiter != nullptr. BT_LOOP_WHEN(bbw.task_meta->current_waiter.exchange( - NULL, butil::memory_order_acquire) == NULL, + nullptr, butil::memory_order_acquire) == nullptr, 30/*nops before sched_yield*/); #ifdef SHOW_BTHREAD_BUTEX_WAITER_COUNT_IN_VARS num_waiters << -1; diff --git a/src/bthread/butex.h b/src/bthread/butex.h index bf86611ea6..334e0d83aa 100644 --- a/src/bthread/butex.h +++ b/src/bthread/butex.h @@ -36,7 +36,7 @@ static const int64_t MIN_SLEEP_US = 2; // Create a butex which is a futex-like 32-bit primitive for synchronizing // bthreads/pthreads. -// Returns a pointer to 32-bit data, NULL on failure. +// Returns a pointer to 32-bit data, nullptr on failure. // NOTE: all butexes are private(not inter-process). void* butex_create(); @@ -74,7 +74,7 @@ int butex_requeue(void* butex1, void* butex2); // Atomically wait on |butex| if *butex equals |expected_value|, until the // butex is woken up by butex_wake*, or CLOCK_REALTIME reached |abstime| if -// abstime is not NULL. +// abstime is not nullptr. // About |abstime|: // Different from FUTEX_WAIT, butex_wait uses absolute time. // About |prepend|: diff --git a/src/bthread/condition_variable.cpp b/src/bthread/condition_variable.cpp index e04187d346..1441050b30 100644 --- a/src/bthread/condition_variable.cpp +++ b/src/bthread/condition_variable.cpp @@ -46,7 +46,7 @@ extern int bthread_mutex_lock_contended(bthread_mutex_t*); int bthread_cond_init(bthread_cond_t* __restrict c, const bthread_condattr_t*) { - c->m = NULL; + c->m = nullptr; c->seq = bthread::butex_create_checked(); *c->seq = 0; return 0; @@ -54,7 +54,7 @@ int bthread_cond_init(bthread_cond_t* __restrict c, int bthread_cond_destroy(bthread_cond_t* c) { bthread::butex_destroy(c->seq); - c->seq = NULL; + c->seq = nullptr; return 0; } @@ -89,7 +89,7 @@ int bthread_cond_wait(bthread_cond_t* __restrict c, const int expected_seq = ic->seq->load(butil::memory_order_relaxed); if (ic->m.load(butil::memory_order_relaxed) != m) { // bind m to c - bthread_mutex_t* expected_m = NULL; + bthread_mutex_t* expected_m = nullptr; if (!ic->m.compare_exchange_strong( expected_m, m, butil::memory_order_relaxed)) { return EINVAL; @@ -97,7 +97,7 @@ int bthread_cond_wait(bthread_cond_t* __restrict c, } bthread_mutex_unlock(m); int rc1 = 0; - if (bthread::butex_wait(ic->seq, expected_seq, NULL) < 0 && + if (bthread::butex_wait(ic->seq, expected_seq, nullptr) < 0 && errno != EWOULDBLOCK && errno != EINTR/*note*/) { // EINTR should not be returned by cond_*wait according to docs on // pthread, however spurious wake-up is OK, just as we do here @@ -123,7 +123,7 @@ int bthread_cond_timedwait(bthread_cond_t* __restrict c, const int expected_seq = ic->seq->load(butil::memory_order_relaxed); if (ic->m.load(butil::memory_order_relaxed) != m) { // bind m to c - bthread_mutex_t* expected_m = NULL; + bthread_mutex_t* expected_m = nullptr; if (!ic->m.compare_exchange_strong( expected_m, m, butil::memory_order_relaxed)) { return EINVAL; diff --git a/src/bthread/condition_variable.h b/src/bthread/condition_variable.h index fb6bb4bcb5..815f68aeb3 100644 --- a/src/bthread/condition_variable.h +++ b/src/bthread/condition_variable.h @@ -47,7 +47,7 @@ class ConditionVariable { typedef bthread_cond_t* native_handler_type; ConditionVariable() { - CHECK_EQ(0, bthread_cond_init(&_cond, NULL)); + CHECK_EQ(0, bthread_cond_init(&_cond, nullptr)); } ~ConditionVariable() { CHECK_EQ(0, bthread_cond_destroy(&_cond)); diff --git a/src/bthread/countdown_event.cpp b/src/bthread/countdown_event.cpp index 1c2c5952f4..7c975fc6c3 100644 --- a/src/bthread/countdown_event.cpp +++ b/src/bthread/countdown_event.cpp @@ -60,7 +60,7 @@ int CountdownEvent::wait() { if (seen_counter <= 0) { return 0; } - if (butex_wait(_butex, seen_counter, NULL) < 0 && + if (butex_wait(_butex, seen_counter, nullptr) < 0 && errno != EWOULDBLOCK && errno != EINTR) { return errno; } diff --git a/src/bthread/execution_queue.cpp b/src/bthread/execution_queue.cpp index ae6f97b40a..de4069b12a 100644 --- a/src/bthread/execution_queue.cpp +++ b/src/bthread/execution_queue.cpp @@ -78,13 +78,13 @@ void ExecutionQueueBase::start_execute(TaskNode* node) { _high_priority_tasks.fetch_add(1, butil::memory_order_relaxed); } TaskNode* const prev_head = _head.exchange(node, butil::memory_order_release); - if (prev_head != NULL) { + if (prev_head != nullptr) { node->next = prev_head; return; } // Get the right to execute the task, start a bthread to avoid deadlock // or stack overflow - node->next = NULL; + node->next = nullptr; node->q = this; ExecutionQueueVars* const vars = get_execq_vars(); @@ -112,7 +112,7 @@ void ExecutionQueueBase::start_execute(TaskNode* node) { _cond.Signal(); } else { // Start the execution bthread in background once. - if (pthread_create(&_pid, NULL, + if (pthread_create(&_pid, nullptr, _execute_tasks_pthread, node) != 0) { PLOG(FATAL) << "Fail to create pthread"; @@ -145,11 +145,11 @@ void* ExecutionQueueBase::_execute_tasks(void* arg) { ExecutionQueueVars* vars = get_execq_vars(); TaskNode* head = (TaskNode*)arg; ExecutionQueueBase* m = (ExecutionQueueBase*)head->q; - TaskNode* cur_tail = NULL; + TaskNode* cur_tail = nullptr; bool destroy_queue = false; for (;;) { if (head->iterated) { - CHECK(head->next != NULL); + CHECK(head->next != nullptr); TaskNode* saved_head = head; head = head->next; m->return_task_node(saved_head); @@ -166,19 +166,19 @@ void* ExecutionQueueBase::_execute_tasks(void* arg) { sched_yield(); } } else { - rc = m->_execute(head, false, NULL); + rc = m->_execute(head, false, nullptr); } if (rc == ESTOP) { destroy_queue = true; } // Release TaskNode until uniterated task or last task - while (head->next != NULL && head->iterated) { + while (head->next != nullptr && head->iterated) { TaskNode* saved_head = head; head = head->next; m->return_task_node(saved_head); } - if (cur_tail == NULL) { - for (cur_tail = head; cur_tail->next != NULL; + if (cur_tail == nullptr) { + for (cur_tail = head; cur_tail->next != nullptr; cur_tail = cur_tail->next) {} } // break when no more tasks and head has been executed @@ -190,7 +190,7 @@ void* ExecutionQueueBase::_execute_tasks(void* arg) { } } if (destroy_queue) { - CHECK(m->_head.load(butil::memory_order_relaxed) == NULL); + CHECK(m->_head.load(butil::memory_order_relaxed) == nullptr); CHECK(m->_stopped); // Add _join_butex by 2 to make it equal to the next version of the // ExecutionQueue from the same slot so that join with old id would @@ -204,7 +204,7 @@ void* ExecutionQueueBase::_execute_tasks(void* arg) { butil::return_resource(slot_of_id(m->_this_id)); } vars->execq_active_count << -1; - return NULL; + return nullptr; } void* ExecutionQueueBase::_execute_tasks_pthread(void* arg) { @@ -218,7 +218,7 @@ void* ExecutionQueueBase::_execute_tasks_pthread(void* arg) { m->_cond.Wait(); } _execute_tasks(m->_current_head); - m->_current_head = NULL; + m->_current_head = nullptr; int expected = _version_of_id(m->_this_id); if (expected != m->_join_butex->load(butil::memory_order_relaxed)) { @@ -226,7 +226,7 @@ void* ExecutionQueueBase::_execute_tasks_pthread(void* arg) { break; } } - return NULL; + return nullptr; } void ExecutionQueueBase::return_task_node(TaskNode* node) { @@ -239,7 +239,7 @@ void ExecutionQueueBase::_on_recycle() { // Push a closed tasks while (true) { TaskNode* node = butil::get_object(); - if (BAIDU_LIKELY(node != NULL)) { + if (BAIDU_LIKELY(node != nullptr)) { get_execq_vars()->running_task_count << 1; node->stop_task = true; node->high_priority = false; @@ -255,21 +255,21 @@ void ExecutionQueueBase::_on_recycle() { int ExecutionQueueBase::join(uint64_t id) { const slot_id_t slot = slot_of_id(id); ExecutionQueueBase* const m = butil::address_resource(slot); - if (m == NULL) { + if (m == nullptr) { // The queue is not created yet, this join is definitely wrong. return EINVAL; } int expected = _version_of_id(id); // acquire fence makes this thread see changes before changing _join_butex. while (expected == m->_join_butex->load(butil::memory_order_acquire)) { - if (butex_wait(m->_join_butex, expected, NULL) < 0 && + if (butex_wait(m->_join_butex, expected, nullptr) < 0 && errno != EWOULDBLOCK && errno != EINTR) { return errno; } } // Join pthread if it's started. if (m->_options.use_pthread && m->_pthread_started) { - pthread_join(m->_pid, NULL); + pthread_join(m->_pid, nullptr); } return 0; } @@ -281,7 +281,7 @@ int ExecutionQueueBase::stop() { if (_version_of_vref(vref) != id_ver) { return EINVAL; } - // Try to set version=id_ver+1 (to make later address() return NULL), + // Try to set version=id_ver+1 (to make later address() return nullptr), // retry on fail. if (_versioned_ref.compare_exchange_strong( vref, _make_vref(id_ver + 1, _ref_of_vref(vref)), @@ -300,11 +300,11 @@ int ExecutionQueueBase::stop() { } int ExecutionQueueBase::_execute(TaskNode* head, bool high_priority, int* niterated) { - if (head != NULL && head->stop_task) { - CHECK(head->next == NULL); + if (head != nullptr && head->stop_task) { + CHECK(head->next == nullptr); head->iterated = true; head->status = TaskNode::EXECUTED; - TaskIteratorBase iter(NULL, this, true, false); + TaskIteratorBase iter(nullptr, this, true, false); _execute_func(_meta, _type_specific_function, iter); if (niterated) { *niterated = 1; @@ -336,7 +336,7 @@ ExecutionQueueBase::scoped_ptr_t ExecutionQueueBase::address(uint64_t id) { scoped_ptr_t ret; const slot_id_t slot = slot_of_id(id); ExecutionQueueBase* const m = butil::address_resource(slot); - if (BAIDU_LIKELY(m != NULL)) { + if (BAIDU_LIKELY(m != nullptr)) { // acquire fence makes sure this thread sees latest changes before // _dereference() const uint64_t vref1 = m->_versioned_ref.fetch_add( @@ -386,21 +386,21 @@ int ExecutionQueueBase::create(uint64_t* id, const ExecutionQueueOptions* option execute_func_t execute_func, clear_task_mem clear_func, void* meta, void* type_specific_function) { - if (execute_func == NULL || clear_func == NULL) { + if (execute_func == nullptr || clear_func == nullptr) { return EINVAL; } slot_id_t slot; ExecutionQueueBase* const m = butil::get_resource(&slot, Forbidden()); - if (BAIDU_LIKELY(m != NULL)) { + if (BAIDU_LIKELY(m != nullptr)) { m->_execute_func = execute_func; m->_clear_func = clear_func; m->_meta = meta; m->_type_specific_function = type_specific_function; - CHECK(m->_head.load(butil::memory_order_relaxed) == NULL); + CHECK(m->_head.load(butil::memory_order_relaxed) == nullptr); CHECK_EQ(0, m->_high_priority_tasks.load(butil::memory_order_relaxed)); ExecutionQueueOptions opt; - if (options != NULL) { + if (options != nullptr) { opt = *options; } m->_options = opt; @@ -410,7 +410,7 @@ int ExecutionQueueBase::create(uint64_t* id, const ExecutionQueueOptions* option 1, butil::memory_order_release)), slot); *id = m->_this_id; m->_pthread_started = false; - m->_current_head = NULL; + m->_current_head = nullptr; get_execq_vars()->execq_count << 1; return 0; } @@ -465,7 +465,7 @@ TaskIteratorBase::~TaskIteratorBase() { } _head = _head->next; } - if (_should_break && _cur_node != NULL + if (_should_break && _cur_node != nullptr && _cur_node->high_priority == _high_priority && _cur_node->iterated) { _cur_node->set_executed(); } diff --git a/src/bthread/execution_queue.h b/src/bthread/execution_queue.h index 5ceef89f9d..6a6c6ce175 100644 --- a/src/bthread/execution_queue.h +++ b/src/bthread/execution_queue.h @@ -146,16 +146,16 @@ struct ExecutionQueueOptions { bool use_pthread; // Attribute of the bthread which execute runs on. default: BTHREAD_ATTR_NORMAL - // Bthread will be used when executor = NULL and use_pthread == false. + // Bthread will be used when executor = nullptr and use_pthread == false. bthread_attr_t bthread_attr; - // Executor that tasks run on. default: NULL + // Executor that tasks run on. default: nullptr // Note that TaskOptions.in_place_if_possible = false will not work, if implementation of // Executor is in-place(synchronous). Executor * executor; }; -// Start an ExecutionQueue. If |options| is NULL, the queue will be created with +// Start an ExecutionQueue. If |options| is nullptr, the queue will be created with // the default options. // Returns 0 on success, errno otherwise // NOTE: type |T| can be non-POD but must be copy-constructive @@ -190,8 +190,8 @@ int execution_queue_execute(ExecutionQueueId id, // Thread-safe and Wait-free. // Execute a task with options. e.g // bthread::execution_queue_execute(queue, task, &bthread::TASK_OPTIONS_URGENT) -// If |options| is NULL, we will use default options (normal task) -// If |handle| is not NULL, we will assign it with the handler of this task. +// If |options| is nullptr, we will use default options (normal task) +// If |handle| is not nullptr, we will assign it with the handler of this task. template int execution_queue_execute(ExecutionQueueId id, typename butil::add_const_reference::type task, diff --git a/src/bthread/execution_queue_inl.h b/src/bthread/execution_queue_inl.h index 9c12e19256..1a41f7d59a 100644 --- a/src/bthread/execution_queue_inl.h +++ b/src/bthread/execution_queue_inl.h @@ -58,7 +58,7 @@ struct BAIDU_CACHELINE_ALIGNMENT TaskNode { , high_priority(false) , in_place(false) , next(UNCONNECTED) - , q(NULL) + , q(nullptr) {} ~TaskNode() {} int cancel(int64_t expected_version) { @@ -103,7 +103,7 @@ struct BAIDU_CACHELINE_ALIGNMENT TaskNode { clear_func(this); CHECK(iterated); } - q = NULL; + q = nullptr; std::unique_lock lck(mutex); ++version; const int saved_status = status; @@ -159,7 +159,7 @@ struct Forbidden {}; friend class TaskIteratorBase; struct Dereferencer { void operator()(ExecutionQueueBase* queue) { - if (queue != NULL) { + if (queue != nullptr) { queue->dereference(); } } @@ -167,12 +167,12 @@ friend class TaskIteratorBase; public: // User cannot create ExecutionQueue fron construct ExecutionQueueBase(Forbidden) - : _head(NULL) + : _head(nullptr) , _versioned_ref(0) // join() depends on even version , _high_priority_tasks(0) , _pthread_started(false) , _cond(&_mutex) - , _current_head(NULL) { + , _current_head(nullptr) { _join_butex = butex_create_checked >(); _join_butex->store(0, butil::memory_order_relaxed); } @@ -258,7 +258,7 @@ friend class TaskIterator; typedef ExecutionQueue self_type; struct Dereferencer { void operator()(self_type* queue) { - if (queue != NULL) { + if (queue != nullptr) { queue->dereference(); } } @@ -297,7 +297,7 @@ friend class TaskIterator; } int execute(typename butil::add_const_reference::type task) { - return execute(task, NULL, NULL); + return execute(task, nullptr, nullptr); } int execute(typename butil::add_const_reference::type task, @@ -307,7 +307,7 @@ friend class TaskIterator; int execute(T&& task) { - return execute(std::forward(task), NULL, NULL); + return execute(std::forward(task), nullptr, nullptr); } int execute(T&& task, @@ -316,7 +316,7 @@ friend class TaskIterator; return EINVAL; } TaskNode* node = allocate_node(); - if (BAIDU_UNLIKELY(node == NULL)) { + if (BAIDU_UNLIKELY(node == nullptr)) { return ENOMEM; } void* const mem = allocator::allocate(node); @@ -344,7 +344,7 @@ friend class TaskIterator; inline ExecutionQueueOptions::ExecutionQueueOptions() : use_pthread(false) , bthread_attr(BTHREAD_ATTR_NORMAL) - , executor(NULL) + , executor(nullptr) {} template @@ -364,14 +364,14 @@ execution_queue_address(ExecutionQueueId id) { template inline int execution_queue_execute(ExecutionQueueId id, typename butil::add_const_reference::type task) { - return execution_queue_execute(id, task, NULL); + return execution_queue_execute(id, task, nullptr); } template inline int execution_queue_execute(ExecutionQueueId id, typename butil::add_const_reference::type task, const TaskOptions* options) { - return execution_queue_execute(id, task, options, NULL); + return execution_queue_execute(id, task, options, nullptr); } template @@ -380,7 +380,7 @@ inline int execution_queue_execute(ExecutionQueueId id, const TaskOptions* options, TaskHandle* handle) { typename ExecutionQueue::scoped_ptr_t ptr = ExecutionQueue::address(id); - if (ptr != NULL) { + if (ptr != nullptr) { return ptr->execute(task, options, handle); } else { return EINVAL; @@ -389,13 +389,13 @@ inline int execution_queue_execute(ExecutionQueueId id, template inline int execution_queue_execute(ExecutionQueueId id, T&& task) { - return execution_queue_execute(id, std::forward(task), NULL); + return execution_queue_execute(id, std::forward(task), nullptr); } template inline int execution_queue_execute(ExecutionQueueId id, T&& task, const TaskOptions* options) { - return execution_queue_execute(id, std::forward(task), options, NULL); + return execution_queue_execute(id, std::forward(task), options, nullptr); } template @@ -404,7 +404,7 @@ inline int execution_queue_execute(ExecutionQueueId id, T&& task, TaskHandle* handle) { typename ExecutionQueue::scoped_ptr_t ptr = ExecutionQueue::address(id); - if (ptr != NULL) { + if (ptr != nullptr) { return ptr->execute(std::forward(task), options, handle); } else { return EINVAL; @@ -415,7 +415,7 @@ template inline int execution_queue_stop(ExecutionQueueId id) { typename ExecutionQueue::scoped_ptr_t ptr = ExecutionQueue::address(id); - if (ptr != NULL) { + if (ptr != nullptr) { return ptr->stop(); } else { return EINVAL; @@ -440,7 +440,7 @@ inline TaskOptions::TaskOptions(bool high_priority, bool in_place_if_possible) //--------------------- TaskIterator ------------------------ inline TaskIteratorBase::operator bool() const { - return !_is_stopped && !_should_break && _cur_node != NULL + return !_is_stopped && !_should_break && _cur_node != nullptr && !_cur_node->stop_task; } @@ -463,12 +463,12 @@ void TaskIterator::operator++(int) { } inline TaskHandle::TaskHandle() - : node(NULL) + : node(nullptr) , version(0) {} inline int execution_queue_cancel(const TaskHandle& h) { - if (h.node == NULL) { + if (h.node == nullptr) { return -1; } return h.node->cancel(h.version); @@ -479,10 +479,10 @@ inline bool ExecutionQueueBase::_more_tasks( TaskNode* old_head, TaskNode** new_tail, bool has_uniterated) { - CHECK(old_head->next == NULL); - // Try to set _head to NULL to mark that the execute is done. + CHECK(old_head->next == nullptr); + // Try to set _head to nullptr to mark that the execute is done. TaskNode* new_head = old_head; - TaskNode* desired = NULL; + TaskNode* desired = nullptr; bool return_when_no_more = false; if (has_uniterated) { desired = old_head; @@ -499,7 +499,7 @@ inline bool ExecutionQueueBase::_more_tasks( // Someone added new requests. // Reverse the list until old_head. - TaskNode* tail = NULL; + TaskNode* tail = nullptr; if (new_tail) { *new_tail = new_head; } @@ -513,7 +513,7 @@ inline bool ExecutionQueueBase::_more_tasks( p->next = tail; tail = p; p = saved_next; - CHECK(p != NULL); + CHECK(p != nullptr); } while (p != old_head); // Link old list with new list. diff --git a/src/bthread/fd.cpp b/src/bthread/fd.cpp index 36e9b313e4..b9c35166a5 100644 --- a/src/bthread/fd.cpp +++ b/src/bthread/fd.cpp @@ -60,21 +60,17 @@ class LazyArray { butil::atomic* get_or_new(size_t index) { const size_t block_index = index / BLOCK_SIZE; if (block_index >= NBLOCK) { - return NULL; + return nullptr; } const size_t block_offset = index - block_index * BLOCK_SIZE; Block* b = _blocks[block_index].load(butil::memory_order_consume); - if (b != NULL) { + if (b != nullptr) { return b->items + block_offset; } - b = new (std::nothrow) Block; - if (NULL == b) { - b = _blocks[block_index].load(butil::memory_order_consume); - return (b ? b->items + block_offset : NULL); - } + b = new Block; // Set items to default value of T. std::fill(b->items, b->items + BLOCK_SIZE, T()); - Block* expected = NULL; + Block* expected = nullptr; if (_blocks[block_index].compare_exchange_strong( expected, b, butil::memory_order_release, butil::memory_order_consume)) { @@ -89,11 +85,11 @@ class LazyArray { if (__builtin_expect(block_index < NBLOCK, 1)) { const size_t block_offset = index - block_index * BLOCK_SIZE; Block* const b = _blocks[block_index].load(butil::memory_order_consume); - if (__builtin_expect(b != NULL, 1)) { + if (__builtin_expect(b != nullptr, 1)) { return b->items + block_offset; } } - return NULL; + return nullptr; } private: @@ -178,21 +174,21 @@ class EpollThread { return -1; } #if defined(OS_LINUX) - epoll_event evt = { EPOLLOUT, { NULL } }; + epoll_event evt = { EPOLLOUT, { nullptr } }; if (epoll_ctl(saved_epfd, EPOLL_CTL_ADD, closing_epoll_pipe[1], &evt) < 0) { #elif defined(OS_MACOSX) struct kevent kqueue_event; EV_SET(&kqueue_event, closing_epoll_pipe[1], EVFILT_WRITE, EV_ADD | EV_ENABLE, - 0, 0, NULL); - if (kevent(saved_epfd, &kqueue_event, 1, NULL, 0, NULL) < 0) { + 0, 0, nullptr); + if (kevent(saved_epfd, &kqueue_event, 1, nullptr, 0, nullptr) < 0) { #endif PLOG(FATAL) << "Fail to add closing_epoll_pipe into epfd=" << saved_epfd; return -1; } - const int rc = bthread_join(_tid, NULL); + const int rc = bthread_join(_tid, nullptr); if (rc) { LOG(FATAL) << "Fail to join EpollThread, " << berror(rc); return -1; @@ -205,19 +201,19 @@ class EpollThread { int fd_wait(int fd, unsigned events, const timespec* abstime) { butil::atomic* p = fd_butexes.get_or_new(fd); - if (NULL == p) { + if (nullptr == p) { errno = ENOMEM; return -1; } EpollButex* butex = p->load(butil::memory_order_consume); - if (NULL == butex) { + if (nullptr == butex) { // It is rare to wait on one file descriptor from multiple threads // simultaneously. Creating singleton by optimistic locking here // saves mutexes for each butex. butex = butex_create_checked(); butex->store(0, butil::memory_order_relaxed); - EpollButex* expected = NULL; + EpollButex* expected = nullptr; if (!p->compare_exchange_strong(expected, butex, butil::memory_order_release, butil::memory_order_consume)) { @@ -261,7 +257,7 @@ class EpollThread { struct kevent kqueue_event; EV_SET(&kqueue_event, fd, events, EV_ADD | EV_ENABLE | EV_ONESHOT, 0, 0, butex); - if (kevent(_epfd, &kqueue_event, 1, NULL, 0, NULL) < 0) { + if (kevent(_epfd, &kqueue_event, 1, nullptr, 0, nullptr) < 0) { PLOG(FATAL) << "Fail to add fd=" << fd << " into kqueuefd=" << _epfd; return -1; } @@ -282,7 +278,7 @@ class EpollThread { return -1; } butil::atomic* pbutex = bthread::fd_butexes.get(fd); - if (NULL == pbutex) { + if (nullptr == pbutex) { // Did not call bthread_fd functions, close directly. return close(fd); } @@ -293,18 +289,18 @@ class EpollThread { errno = EBADF; return -1; } - if (butex != NULL) { + if (butex != nullptr) { butex->fetch_add(1, butil::memory_order_relaxed); butex_wake_all(butex); } #if defined(OS_LINUX) - epoll_ctl(_epfd, EPOLL_CTL_DEL, fd, NULL); + epoll_ctl(_epfd, EPOLL_CTL_DEL, fd, nullptr); #elif defined(OS_MACOSX) struct kevent evt; - EV_SET(&evt, fd, EVFILT_WRITE, EV_DELETE, 0, 0, NULL); - kevent(_epfd, &evt, 1, NULL, 0, NULL); - EV_SET(&evt, fd, EVFILT_READ, EV_DELETE, 0, 0, NULL); - kevent(_epfd, &evt, 1, NULL, 0, NULL); + EV_SET(&evt, fd, EVFILT_WRITE, EV_DELETE, 0, 0, nullptr); + kevent(_epfd, &evt, 1, nullptr, 0, nullptr); + EV_SET(&evt, fd, EVFILT_READ, EV_DELETE, 0, 0, nullptr); + kevent(_epfd, &evt, 1, nullptr, 0, nullptr); #endif const int rc = close(fd); pbutex->exchange(butex, butil::memory_order_relaxed); @@ -324,15 +320,11 @@ class EpollThread { const int initial_epfd = _epfd; const size_t MAX_EVENTS = 32; #if defined(OS_LINUX) - epoll_event* e = new (std::nothrow) epoll_event[MAX_EVENTS]; + epoll_event* e = new epoll_event[MAX_EVENTS]; #elif defined(OS_MACOSX) typedef struct kevent KEVENT; - struct kevent* e = new (std::nothrow) KEVENT[MAX_EVENTS]; + struct kevent* e = new KEVENT[MAX_EVENTS]; #endif - if (NULL == e) { - LOG(FATAL) << "Fail to new epoll_event"; - return NULL; - } #if defined(OS_LINUX) # ifndef BAIDU_KERNEL_FIXED_EPOLLONESHOT_BUG @@ -344,7 +336,7 @@ class EpollThread { #if defined(OS_LINUX) const int n = epoll_wait(epfd, e, MAX_EVENTS, -1); #elif defined(OS_MACOSX) - const int n = kevent(epfd, NULL, 0, e, MAX_EVENTS, NULL); + const int n = kevent(epfd, nullptr, 0, e, MAX_EVENTS, nullptr); #endif if (_stop) { break; @@ -370,7 +362,7 @@ class EpollThread { #if defined(OS_LINUX) # ifndef BAIDU_KERNEL_FIXED_EPOLLONESHOT_BUG for (int i = 0; i < n; ++i) { - epoll_ctl(epfd, EPOLL_CTL_DEL, e[i].data.fd, NULL); + epoll_ctl(epfd, EPOLL_CTL_DEL, e[i].data.fd, nullptr); } # endif #endif @@ -381,12 +373,12 @@ class EpollThread { # else butil::atomic* pbutex = fd_butexes.get(e[i].data.fd); EpollButex* butex = pbutex ? - pbutex->load(butil::memory_order_consume) : NULL; + pbutex->load(butil::memory_order_consume) : nullptr; # endif #elif defined(OS_MACOSX) EpollButex* butex = static_cast(e[i].udata); #endif - if (butex != NULL && butex != CLOSING_GUARD) { + if (butex != nullptr && butex != CLOSING_GUARD) { butex->fetch_add(1, butil::memory_order_relaxed); butex_wake_all(butex); } @@ -396,7 +388,7 @@ class EpollThread { delete [] e; DLOG(INFO) << "EpollThread=" << _tid << "(epfd=" << initial_epfd << ") is about to stop"; - return NULL; + return nullptr; } int _epfd; @@ -447,16 +439,16 @@ int bthread_fd_wait(int fd, unsigned events) { return -1; } bthread::TaskGroup* g = bthread::BAIDU_GET_VOLATILE_THREAD_LOCAL(tls_task_group); - if (NULL != g && !g->is_current_pthread_task()) { + if (nullptr != g && !g->is_current_pthread_task()) { return bthread::get_epoll_thread(fd).fd_wait( - fd, events, NULL); + fd, events, nullptr); } - return bthread::pthread_fd_wait(fd, events, NULL); + return bthread::pthread_fd_wait(fd, events, nullptr); } int bthread_fd_timedwait(int fd, unsigned events, const timespec* abstime) { - if (NULL == abstime) { + if (nullptr == abstime) { return bthread_fd_wait(fd, events); } if (fd < 0) { @@ -464,7 +456,7 @@ int bthread_fd_timedwait(int fd, unsigned events, return -1; } bthread::TaskGroup* g = bthread::BAIDU_GET_VOLATILE_THREAD_LOCAL(tls_task_group); - if (NULL != g && !g->is_current_pthread_task()) { + if (nullptr != g && !g->is_current_pthread_task()) { return bthread::get_epoll_thread(fd).fd_wait( fd, events, abstime); } @@ -474,7 +466,7 @@ int bthread_fd_timedwait(int fd, unsigned events, int bthread_connect(int sockfd, const sockaddr* serv_addr, socklen_t addrlen) { bthread::TaskGroup* g = bthread::BAIDU_GET_VOLATILE_THREAD_LOCAL(tls_task_group); - if (NULL == g || g->is_current_pthread_task()) { + if (nullptr == g || g->is_current_pthread_task()) { return ::connect(sockfd, serv_addr, addrlen); } diff --git a/src/bthread/id.cpp b/src/bthread/id.cpp index 7aabed6837..9a97dc8f95 100644 --- a/src/bthread/id.cpp +++ b/src/bthread/id.cpp @@ -33,10 +33,10 @@ namespace bthread { template class SmallQueue { public: - SmallQueue() : _begin(0), _size(0), _full(NULL) {} + SmallQueue() : _begin(0), _size(0), _full(nullptr) {} void push(const T& val) { - if (_full != NULL && !_full->empty()) { + if (_full != nullptr && !_full->empty()) { _full->push_back(val); } else if (_size < N) { int tail = _begin + _size; @@ -46,7 +46,7 @@ class SmallQueue { _c[tail] = val; ++_size; } else { - if (_full == NULL) { + if (_full == nullptr) { _full = new std::deque; } _full->push_back(val); @@ -69,7 +69,7 @@ class SmallQueue { return false; } bool empty() const { - return _size == 0 && (_full == NULL || _full->empty()); + return _size == 0 && (_full == nullptr || _full->empty()); } size_t size() const { @@ -86,7 +86,7 @@ class SmallQueue { ~SmallQueue() { delete _full; - _full = NULL; + _full = nullptr; } private: @@ -104,7 +104,7 @@ struct PendingError { std::string error_text; const char *location; - PendingError() : id(INVALID_BTHREAD_ID), error_code(0), location(NULL) {} + PendingError() : id(INVALID_BTHREAD_ID), error_code(0), location(nullptr) {} }; struct BAIDU_CACHELINE_ALIGNMENT Id { @@ -169,7 +169,7 @@ inline uint32_t get_version(bthread_id_t id) { inline bool id_exists_with_true_negatives(bthread_id_t id) { Id* const meta = address_resource(get_slot(id)); - if (meta == NULL) { + if (meta == nullptr) { return false; } const uint32_t id_ver = bthread::get_version(id); @@ -178,7 +178,7 @@ inline bool id_exists_with_true_negatives(bthread_id_t id) { // required by unittest uint32_t id_value(bthread_id_t id) { Id* const meta = address_resource(get_slot(id)); - if (meta != NULL) { + if (meta != nullptr) { return *meta->butex; } return 0; // valid version never be zero @@ -201,14 +201,14 @@ void id_status(bthread_id_t id, std::ostream &os) { const uint32_t id_ver = bthread::get_version(id); uint32_t* butex = meta->butex; bool valid = true; - void* data = NULL; - int (*on_error)(bthread_id_t, void*, int) = NULL; - int (*on_error2)(bthread_id_t, void*, int, const std::string&) = NULL; + void* data = nullptr; + int (*on_error)(bthread_id_t, void*, int) = nullptr; + int (*on_error2)(bthread_id_t, void*, int, const std::string&) = nullptr; uint32_t first_ver = 0; uint32_t locked_ver = 0; uint32_t unlockable_ver = 0; uint32_t contended_ver = 0; - const char *lock_location = NULL; + const char *lock_location = nullptr; SmallQueue pending_q; uint32_t butex_value = 0; @@ -314,7 +314,7 @@ struct IdResetter { }; size_t get_sizes(const bthread_id_list_t* list, size_t* cnt, size_t n) { - if (list->impl == NULL) { + if (list->impl == nullptr) { return 0; } return static_cast(list->impl)->get_sizes(cnt, n); @@ -390,7 +390,7 @@ int bthread_id_create( int (*on_error)(bthread_id_t, void*, int)) { return bthread::id_create_impl( id, data, - (on_error ? on_error : bthread::default_bthread_id_on_error), NULL); + (on_error ? on_error : bthread::default_bthread_id_on_error), nullptr); } int bthread_id_create_ranged(bthread_id_t* id, void* data, @@ -399,7 +399,7 @@ int bthread_id_create_ranged(bthread_id_t* id, void* data, return bthread::id_create_ranged_impl( id, data, (on_error ? on_error : bthread::default_bthread_id_on_error), - NULL, range); + nullptr, range); } int bthread_id_lock_and_reset_range_verbose( @@ -440,7 +440,7 @@ int bthread_id_lock_and_reset_range_verbose( uint32_t expected_ver = *butex; meta->mutex.unlock(); ever_contended = true; - if (bthread::butex_wait(butex, expected_ver, NULL) < 0 && + if (bthread::butex_wait(butex, expected_ver, nullptr) < 0 && errno != EWOULDBLOCK && errno != EINTR) { return errno; } @@ -527,7 +527,7 @@ int bthread_id_join(bthread_id_t id) { if (!has_ver) { break; } - if (bthread::butex_wait(join_butex, expected_ver, NULL) < 0 && + if (bthread::butex_wait(join_butex, expected_ver, nullptr) < 0 && errno != EWOULDBLOCK && errno != EINTR) { return errno; } @@ -553,7 +553,7 @@ int bthread_id_trylock(bthread_id_t id, void** pdata) { } *butex = meta->locked_ver; meta->mutex.unlock(); - if (pdata != NULL) { + if (pdata != nullptr) { *pdata = meta->data; } return 0; @@ -642,7 +642,7 @@ int bthread_id_unlock_and_destroy(bthread_id_t id) { int bthread_id_list_init(bthread_id_list_t* list, unsigned /*size*/, unsigned /*conflict_size*/) { - list->impl = NULL; // create on demand. + list->impl = nullptr; // create on demand. // Set unused fields to zero as well. list->head = 0; list->size = 0; @@ -653,15 +653,12 @@ int bthread_id_list_init(bthread_id_list_t* list, void bthread_id_list_destroy(bthread_id_list_t* list) { delete static_cast(list->impl); - list->impl = NULL; + list->impl = nullptr; } int bthread_id_list_add(bthread_id_list_t* list, bthread_id_t id) { - if (list->impl == NULL) { - list->impl = new (std::nothrow) bthread::IdList; - if (NULL == list->impl) { - return ENOMEM; - } + if (list->impl == nullptr) { + list->impl = new bthread::IdList; } return static_cast(list->impl)->add(id); } @@ -693,7 +690,7 @@ int bthread_id_create2( bthread_id_t* id, void* data, int (*on_error)(bthread_id_t, void*, int, const std::string&)) { return bthread::id_create_impl( - id, data, NULL, + id, data, nullptr, (on_error ? on_error : bthread::default_bthread_id_on_error2)); } @@ -702,7 +699,7 @@ int bthread_id_create2_ranged( int (*on_error)(bthread_id_t, void*, int, const std::string&), int range) { return bthread::id_create_ranged_impl( - id, data, NULL, + id, data, nullptr, (on_error ? on_error : bthread::default_bthread_id_on_error2), range); } @@ -744,7 +741,7 @@ int bthread_id_error2_verbose(bthread_id_t id, int error_code, int bthread_id_list_reset2(bthread_id_list_t* list, int error_code, const std::string& error_text) { - if (list->impl != NULL) { + if (list->impl != nullptr) { static_cast(list->impl)->apply( bthread::IdResetter(error_code, error_text)); } @@ -755,10 +752,10 @@ int bthread_id_list_reset2_pthreadsafe(bthread_id_list_t* list, int error_code, const std::string& error_text, pthread_mutex_t* mutex) { - if (mutex == NULL) { + if (mutex == nullptr) { return EINVAL; } - if (list->impl == NULL) { + if (list->impl == nullptr) { return 0; } bthread_id_list_t tmplist; @@ -779,10 +776,10 @@ int bthread_id_list_reset2_bthreadsafe(bthread_id_list_t* list, int error_code, const std::string& error_text, bthread_mutex_t* mutex) { - if (mutex == NULL) { + if (mutex == nullptr) { return EINVAL; } - if (list->impl == NULL) { + if (list->impl == nullptr) { return 0; } bthread_id_list_t tmplist; diff --git a/src/bthread/id.h b/src/bthread/id.h index f9fef65a42..4340bc1c4b 100644 --- a/src/bthread/id.h +++ b/src/bthread/id.h @@ -35,7 +35,7 @@ __BEGIN_DECLS // It's slower than mutex and not proper for general synchronizations. // ---------------------------------------------------------------------- -// Create a bthread_id_t and put it into *id. Crash when `id' is NULL. +// Create a bthread_id_t and put it into *id. Crash when `id' is nullptr. // id->value will never be zero. // `on_error' will be called after bthread_id_error() is called. // ------------------------------------------------------------------------- diff --git a/src/bthread/key.cpp b/src/bthread/key.cpp index dd62ce47ab..8db23e0816 100644 --- a/src/bthread/key.cpp +++ b/src/bthread/key.cpp @@ -104,9 +104,9 @@ class BAIDU_CACHELINE_ALIGNMENT SubKeyTable { for (uint32_t i = 0; i < KEY_2NDLEVEL_SIZE; ++i) { void* p = _data[i].ptr; if (p) { - // Set the position to NULL before calling dtor which may set + // Set the position to nullptr before calling dtor which may set // the position again. - _data[i].ptr = NULL; + _data[i].ptr = nullptr; KeyInfo info = bthread::s_key_info[offset + i]; if (info.dtor && _data[i].version == info.version) { @@ -131,7 +131,7 @@ class BAIDU_CACHELINE_ALIGNMENT SubKeyTable { if (_data[index].version == version) { return _data[index].ptr; } - return NULL; + return nullptr; } inline void set_data(uint32_t index, uint32_t version, void* data) { _data[index].version = version; @@ -150,7 +150,7 @@ class BAIDU_CACHELINE_ALIGNMENT SubKeyTable { // Align with cacheline to avoid false sharing. class BAIDU_CACHELINE_ALIGNMENT KeyTable { public: - KeyTable() : next(NULL) { + KeyTable() : next(nullptr) { memset(_subs, 0, sizeof(_subs)); nkeytable.fetch_add(1, butil::memory_order_relaxed); } @@ -165,7 +165,7 @@ class BAIDU_CACHELINE_ALIGNMENT KeyTable { } bool all_cleared = true; for (uint32_t i = 0; i < KEY_1STLEVEL_SIZE; ++i) { - if (_subs[i] != NULL && !_subs[i]->cleared()) { + if (_subs[i] != nullptr && !_subs[i]->cleared()) { all_cleared = false; break; } @@ -189,7 +189,7 @@ class BAIDU_CACHELINE_ALIGNMENT KeyTable { key.index - subidx * KEY_2NDLEVEL_SIZE, key.version); } } - return NULL; + return nullptr; } inline int set_data(bthread_key_t key, void* data) { @@ -197,11 +197,8 @@ class BAIDU_CACHELINE_ALIGNMENT KeyTable { if (subidx < KEY_1STLEVEL_SIZE && key.version == s_key_info[key.index].version) { SubKeyTable* sub_kt = _subs[subidx]; - if (sub_kt == NULL) { - sub_kt = new (std::nothrow) SubKeyTable; - if (NULL == sub_kt) { - return ENOMEM; - } + if (sub_kt == nullptr) { + sub_kt = new SubKeyTable; _subs[subidx] = sub_kt; } sub_kt->set_data(key.index - subidx * KEY_2NDLEVEL_SIZE, @@ -221,7 +218,7 @@ class BAIDU_CACHELINE_ALIGNMENT KeyTable { class BAIDU_CACHELINE_ALIGNMENT KeyTableList { public: KeyTableList() : - _head(NULL), _tail(NULL), _length(0) {} + _head(nullptr), _tail(nullptr), _length(0) {} ~KeyTableList() { TaskGroup* g = BAIDU_GET_VOLATILE_THREAD_LOCAL(tls_task_group); @@ -236,7 +233,7 @@ class BAIDU_CACHELINE_ALIGNMENT KeyTableList { } delete kt; if (old_kt == kt) { - old_kt = NULL; + old_kt = nullptr; } g = BAIDU_GET_VOLATILE_THREAD_LOCAL(tls_task_group); } @@ -247,57 +244,57 @@ class BAIDU_CACHELINE_ALIGNMENT KeyTableList { } void append(KeyTable* keytable) { - if (keytable == NULL) { + if (keytable == nullptr) { return; } - if (_head == NULL) { + if (_head == nullptr) { _head = _tail = keytable; } else { _tail->next = keytable; _tail = keytable; } - keytable->next = NULL; + keytable->next = nullptr; _length++; } KeyTable* remove_front() { - if (_head == NULL) { - return NULL; + if (_head == nullptr) { + return nullptr; } KeyTable* temp = _head; _head = _head->next; _length--; - if (_head == NULL) { - _tail = NULL; + if (_head == nullptr) { + _tail = nullptr; } return temp; } int move_first_n_to_target(KeyTable** target, uint32_t size) { - if (size > _length || _head == NULL) { + if (size > _length || _head == nullptr) { return 0; } KeyTable* current = _head; - KeyTable* prev = NULL; + KeyTable* prev = nullptr; uint32_t count = 0; - while (current != NULL && count < size) { + while (current != nullptr && count < size) { prev = current; current = current->next; count++; } - if (prev != NULL) { - if (*target == NULL) { + if (prev != nullptr) { + if (*target == nullptr) { *target = _head; - prev->next = NULL; + prev->next = nullptr; } else { prev->next = *target; *target = _head; } _head = current; _length -= count; - if (_head == NULL) { - _tail = NULL; + if (_head == nullptr) { + _tail = nullptr; } } return count; @@ -311,7 +308,7 @@ class BAIDU_CACHELINE_ALIGNMENT KeyTableList { inline bool check_length() { KeyTable* current = _head; uint32_t count = 0; - while (current != NULL) { + while (current != nullptr) { current = current->next; count++; } @@ -325,7 +322,7 @@ class BAIDU_CACHELINE_ALIGNMENT KeyTableList { }; KeyTable* borrow_keytable(bthread_keytable_pool_t* pool) { - if (pool != NULL && (pool->list || pool->free_keytables)) { + if (pool != nullptr && (pool->list || pool->free_keytables)) { KeyTable* p; { pthread_rwlock_rdlock(&pool->rwlock); @@ -343,7 +340,7 @@ KeyTable* borrow_keytable(bthread_keytable_pool_t* pool) { pthread_rwlock_wrlock(&pool->rwlock); if (pool->destroyed) { pthread_rwlock_unlock(&pool->rwlock); - return NULL; + return nullptr; } auto list = (butil::ThreadLocal*)pool->list; p = (KeyTable*)pool->free_keytables; @@ -378,16 +375,16 @@ KeyTable* borrow_keytable(bthread_keytable_pool_t* pool) { pthread_rwlock_unlock(&pool->rwlock); } } - return NULL; + return nullptr; } // Referenced in task_group.cpp, must be extern. // Caller of this function must hold the KeyTable void return_keytable(bthread_keytable_pool_t* pool, KeyTable* kt) { - if (NULL == kt) { + if (nullptr == kt) { return; } - if (pool == NULL) { + if (pool == nullptr) { delete kt; return; } @@ -407,7 +404,7 @@ void return_keytable(bthread_keytable_pool_t* pool, KeyTable* kt) { if (need_move) { pthread_rwlock_wrlock(&pool->rwlock); auto list = (butil::ThreadLocal*)pool->list; - if (!pool->destroyed && list != NULL && + if (!pool->destroyed && list != nullptr && list->get()->get_length() > FLAGS_key_table_list_size) { int out = list->get()->move_first_n_to_target( (KeyTable**)(&pool->free_keytables), @@ -423,7 +420,7 @@ static void cleanup_pthread(void* arg) { if (kt) { delete kt; // After deletion: tls may be set during deletion. - tls_bls_ptr()->keytable = NULL; + tls_bls_ptr()->keytable = nullptr; } } @@ -446,42 +443,42 @@ static size_t get_keytable_memory(void*) { } static bvar::PassiveStatus s_bthread_key_count( - "bthread_key_count", get_key_count, NULL); + "bthread_key_count", get_key_count, nullptr); static bvar::PassiveStatus s_bthread_keytable_count( - "bthread_keytable_count", get_keytable_count, NULL); + "bthread_keytable_count", get_keytable_count, nullptr); static bvar::PassiveStatus s_bthread_keytable_memory( - "bthread_keytable_memory", get_keytable_memory, NULL); + "bthread_keytable_memory", get_keytable_memory, nullptr); } // namespace bthread extern "C" { int bthread_keytable_pool_init(bthread_keytable_pool_t* pool) { - if (pool == NULL) { + if (pool == nullptr) { LOG(ERROR) << "Param[pool] is NULL"; return EINVAL; } - pthread_rwlock_init(&pool->rwlock, NULL); + pthread_rwlock_init(&pool->rwlock, nullptr); pool->list = new butil::ThreadLocal(); - pool->free_keytables = NULL; + pool->free_keytables = nullptr; pool->size = 0; pool->destroyed = 0; return 0; } int bthread_keytable_pool_destroy(bthread_keytable_pool_t* pool) { - if (pool == NULL) { + if (pool == nullptr) { LOG(ERROR) << "Param[pool] is NULL"; return EINVAL; } - bthread::KeyTable* saved_free_keytables = NULL; + bthread::KeyTable* saved_free_keytables = nullptr; pthread_rwlock_wrlock(&pool->rwlock); pool->destroyed = 1; pool->size = 0; delete (butil::ThreadLocal*)pool->list; saved_free_keytables = (bthread::KeyTable*)pool->free_keytables; - pool->list = NULL; - pool->free_keytables = NULL; + pool->list = nullptr; + pool->free_keytables = nullptr; pthread_rwlock_unlock(&pool->rwlock); // Cheat get/setspecific and destroy the keytables. @@ -510,7 +507,7 @@ int bthread_keytable_pool_destroy(bthread_keytable_pool_t* pool) { int bthread_keytable_pool_getstat(bthread_keytable_pool_t* pool, bthread_keytable_pool_stat_t* stat) { - if (pool == NULL || stat == NULL) { + if (pool == nullptr || stat == nullptr) { LOG(ERROR) << "Param[pool] or Param[stat] is NULL"; return EINVAL; } @@ -521,7 +518,7 @@ int bthread_keytable_pool_getstat(bthread_keytable_pool_t* pool, } int get_thread_local_keytable_list_length(bthread_keytable_pool_t* pool) { - if (pool == NULL) { + if (pool == nullptr) { LOG(ERROR) << "Param[pool] is NULL"; return EINVAL; } @@ -550,7 +547,7 @@ void bthread_keytable_pool_reserve(bthread_keytable_pool_t* pool, bthread_key_t key, void* ctor(const void*), const void* ctor_args) { - if (pool == NULL) { + if (pool == nullptr) { LOG(ERROR) << "Param[pool] is NULL"; return; } @@ -560,10 +557,7 @@ void bthread_keytable_pool_reserve(bthread_keytable_pool_t* pool, return; } for (size_t i = stat.nfree; i < nfree; ++i) { - bthread::KeyTable* kt = new (std::nothrow) bthread::KeyTable; - if (kt == NULL) { - break; - } + bthread::KeyTable* kt = new bthread::KeyTable; void* data = ctor(ctor_args); if (data) { kt->set_data(key, data); @@ -579,7 +573,7 @@ void bthread_keytable_pool_reserve(bthread_keytable_pool_t* pool, pool->free_keytables = kt; ++pool->size; pthread_rwlock_unlock(&pool->rwlock); - if (data == NULL) { + if (data == nullptr) { break; } } @@ -611,8 +605,8 @@ int bthread_key_create2(bthread_key_t* key, } int bthread_key_create(bthread_key_t* key, void (*dtor)(void*)) { - if (dtor == NULL) { - return bthread_key_create2(key, NULL, NULL); + if (dtor == nullptr) { + return bthread_key_create2(key, nullptr, nullptr); } else { return bthread_key_create2(key, bthread::arg_as_dtor, (const void*)dtor); } @@ -626,8 +620,8 @@ int bthread_key_delete(bthread_key_t key) { if (++bthread::s_key_info[key.index].version == 0) { ++bthread::s_key_info[key.index].version; } - bthread::s_key_info[key.index].dtor = NULL; - bthread::s_key_info[key.index].dtor_args = NULL; + bthread::s_key_info[key.index].dtor = nullptr; + bthread::s_key_info[key.index].dtor_args = nullptr; bthread::s_free_keys[bthread::nfreekey++] = key.index; return 0; } @@ -638,16 +632,13 @@ int bthread_key_delete(bthread_key_t key) { // NOTE: Can't borrow_keytable in bthread_setspecific, otherwise following // memory leak may occur: -// -> bthread_getspecific fails to borrow_keytable and returns NULL. +// -> bthread_getspecific fails to borrow_keytable and returns nullptr. // -> bthread_setspecific succeeds to borrow_keytable and overwrites old data // at the position with newly created data, the old data is leaked. int bthread_setspecific(bthread_key_t key, void* data) { bthread::KeyTable* kt = bthread::tls_bls_ptr()->keytable; - if (NULL == kt) { - kt = new (std::nothrow) bthread::KeyTable; - if (NULL == kt) { - return ENOMEM; - } + if (nullptr == kt) { + kt = new bthread::KeyTable; bthread::tls_bls_ptr()->keytable = kt; bthread::TaskGroup* const g = bthread::BAIDU_GET_VOLATILE_THREAD_LOCAL(tls_task_group); if (g) { @@ -680,7 +671,7 @@ void* bthread_getspecific(bthread_key_t key) { return kt->get_data(key); } } - return NULL; + return nullptr; } void bthread_assign_data(void* data) { diff --git a/src/bthread/list_of_abafree_id.h b/src/bthread/list_of_abafree_id.h index 16de5b2009..73c7325563 100644 --- a/src/bthread/list_of_abafree_id.h +++ b/src/bthread/list_of_abafree_id.h @@ -116,20 +116,20 @@ ListOfABAFreeId::ListOfABAFreeId() for (size_t i = 0; i < IdTraits::BLOCK_SIZE; ++i) { _head_block.ids[i] = IdTraits::ID_INIT; } - _head_block.next = NULL; + _head_block.next = nullptr; } template ListOfABAFreeId::~ListOfABAFreeId() { - _cur_block = NULL; + _cur_block = nullptr; _cur_index = 0; _nblock = 0; - for (IdBlock* p = _head_block.next; p != NULL;) { + for (IdBlock* p = _head_block.next; p != nullptr;) { IdBlock* saved_next = p->next; delete p; p = saved_next; } - _head_block.next = NULL; + _head_block.next = nullptr; } template @@ -194,10 +194,7 @@ int ListOfABAFreeId::add(Id id) { // // [..xxxx....] -> [......yyyy] -> [..........] // block A new block block B - IdBlock* new_block = new (std::nothrow) IdBlock; - if (NULL == new_block) { - return ENOMEM; - } + IdBlock* new_block = new IdBlock; ++_nblock; for (size_t i = 0; i < _cur_index; ++i) { new_block->ids[i] = IdTraits::ID_INIT; @@ -229,15 +226,12 @@ int ListOfABAFreeId::add(Id id) { template int ListOfABAFreeId::gc() { - IdBlock* new_block = new (std::nothrow) IdBlock; - if (NULL == new_block) { - return ENOMEM; - } + IdBlock* new_block = new IdBlock; // reset head block for (size_t i = 0; i < IdTraits::BLOCK_SIZE; ++i) { new_block->ids[i] = IdTraits::ID_INIT; } - new_block->next = NULL; + new_block->next = nullptr; TempIdBlock tmp_id_block; tmp_id_block.block = new_block; @@ -285,15 +279,12 @@ int ListOfABAFreeId::add_to_temp_list(TempIdBlock* block_list, Id if (block_list->index == IdTraits::BLOCK_SIZE) { block_list->index = 0; block_list->nblock++; - block_list->block->next = new (std::nothrow) IdBlock; - if (NULL == block_list->block->next) { - return ENOMEM; - } + block_list->block->next = new IdBlock; block_list->block = block_list->block->next; for (size_t i = 0; i < IdTraits::BLOCK_SIZE; ++i) { block_list->block->ids[i] = IdTraits::ID_INIT; } - block_list->block->next = NULL; + block_list->block->next = nullptr; } return 0; } @@ -301,7 +292,7 @@ int ListOfABAFreeId::add_to_temp_list(TempIdBlock* block_list, Id template template int ListOfABAFreeId::for_each(const Fn& fn) { - for (IdBlock* p = &_head_block; p != NULL; p = p->next) { + for (IdBlock* p = &_head_block; p != nullptr; p = p->next) { for (size_t i = 0; i < IdTraits::BLOCK_SIZE; ++i) { if (p->ids[i] != IdTraits::ID_INIT && IdTraits::exists(p->ids[i])) { int rc = fn(p->ids[i]); @@ -317,7 +308,7 @@ int ListOfABAFreeId::for_each(const Fn& fn) { template template void ListOfABAFreeId::apply(const Fn& fn) { - for (IdBlock* p = &_head_block; p != NULL; p = p->next) { + for (IdBlock* p = &_head_block; p != nullptr; p = p->next) { for (size_t i = 0; i < IdTraits::BLOCK_SIZE; ++i) { if (p->ids[i] != IdTraits::ID_INIT && IdTraits::exists(p->ids[i])) { fn(p->ids[i]); @@ -328,7 +319,7 @@ void ListOfABAFreeId::apply(const Fn& fn) { template void ListOfABAFreeId::free_list(IdBlock* p) { - for (; p != NULL;) { + for (; p != nullptr;) { IdBlock* saved_next = p->next; delete p; p = saved_next; diff --git a/src/bthread/mutex.cpp b/src/bthread/mutex.cpp index 1e6d244168..ac8b1d0e86 100644 --- a/src/bthread/mutex.cpp +++ b/src/bthread/mutex.cpp @@ -93,7 +93,7 @@ struct SampledContention : public bvar::Collected { private: friend butil::ObjectPool; SampledContention() - : duration_ns(0), count(0), stack{NULL}, nframes(0), _hash_code(0) {} + : duration_ns(0), count(0), stack{nullptr}, nframes(0), _hash_code(0) {} ~SampledContention() override = default; mutable uint32_t _hash_code; // For combining samples with hashmap. @@ -269,8 +269,8 @@ void ContentionProfiler::flush_to_disk(bool ending) { } // If contention profiler is on, this variable will be set with a valid -// instance. NULL otherwise. -BAIDU_CACHELINE_ALIGNMENT ContentionProfiler* g_cp = NULL; +// instance. nullptr otherwise. +BAIDU_CACHELINE_ALIGNMENT ContentionProfiler* g_cp = nullptr; // Need this version to solve an issue that non-empty entries left by // previous contention profilers should be detected and overwritten. static uint64_t g_cp_version = 0; @@ -323,7 +323,7 @@ static int64_t get_nconflicthash(void*) { // Start profiling contention. bool ContentionProfilerStart(const char* filename) { - if (filename == NULL) { + if (filename == nullptr) { LOG(ERROR) << "Parameter [filename] is NULL"; return false; } @@ -334,7 +334,7 @@ bool ContentionProfilerStart(const char* filename) { // Create related global bvar lazily. static bvar::PassiveStatus g_nconflicthash_var - ("contention_profiler_conflict_hash", get_nconflicthash, NULL); + ("contention_profiler_conflict_hash", get_nconflicthash, nullptr); static bvar::DisplaySamplingRatio g_sampling_ratio_var( "contention_profiler_sampling_ratio", &g_cp_sl); @@ -353,12 +353,12 @@ bool ContentionProfilerStart(const char* filename) { // Stop contention profiler. void ContentionProfilerStop() { - ContentionProfiler* ctx = NULL; + ContentionProfiler* ctx = nullptr; if (g_cp) { std::unique_lock mu(g_cp_mutex); if (g_cp) { ctx = g_cp; - g_cp = NULL; + g_cp = nullptr; mu.unlock(); // make sure it's initialiazed in case no sample was gathered, @@ -605,7 +605,7 @@ add_pthread_contention_site(const Mutex* mutex) { } } g_nconflicthash.fetch_add(1, butil::memory_order_relaxed); - return NULL; + return nullptr; } template @@ -713,7 +713,7 @@ static MutexOwnerMapEntry g_mutex_owner_map[MUTEX_MAP_SIZE] = {}; // zero-initia static void InitMutexOwnerMapEntry(pthread_mutex_t* mutex, const pthread_mutexattr_t* mutexattr) { int type = PTHREAD_MUTEX_DEFAULT; - if (NULL != mutexattr) { + if (nullptr != mutexattr) { pthread_mutexattr_gettype(mutexattr, &type); } // Only normal mutexes are tracked. @@ -740,8 +740,8 @@ static void InitMutexOwnerMapEntry(pthread_mutex_t* mutex, static BUTIL_FORCE_INLINE MutexOwnerMapEntry* FindMutexOwnerMapEntry(pthread_mutex_t* mutex) { - if (NULL == mutex) { - return NULL; + if (nullptr == mutex) { + return nullptr; } // Fast path. @@ -756,12 +756,12 @@ MutexOwnerMapEntry* FindMutexOwnerMapEntry(pthread_mutex_t* mutex) { return &entry; } } - return NULL; + return nullptr; } static void DestroyMutexOwnerMapEntry(pthread_mutex_t* mutex) { MutexOwnerMapEntry* entry = FindMutexOwnerMapEntry(mutex); - if (NULL != entry) { + if (nullptr != entry) { entry->valid.store(false, butil::memory_order_relaxed); } } @@ -776,19 +776,19 @@ static void DestroyMutexOwnerMapEntry(pthread_mutex_t* mutex) { MutexOwnerMapEntry* entry = ::bthread::internal::FindMutexOwnerMapEntry(mutex) #define SYS_PTHREAD_MUTEX_CHECK_OWNER \ - if (NULL != entry) { \ + if (nullptr != entry) { \ PTHREAD_MUTEX_CHECK_OWNER(entry->owner); \ } #define SYS_PTHREAD_MUTEX_SET_OWNER \ - if (NULL != entry) { \ + if (nullptr != entry) { \ PTHREAD_MUTEX_SET_OWNER(entry->owner); \ } #define SYS_PTHREAD_MUTEX_RESET_OWNER(mutex) \ FIND_SYS_PTHREAD_MUTEX_OWNER_MAP_ENTRY(mutex); \ - if (NULL != entry) { \ - MUTEX_RESET_OWNER_COMMON(entry->owner); \ + if (nullptr != entry) { \ + MUTEX_RESET_OWNER_COMMON(entry->owner); \ } #else @@ -805,7 +805,7 @@ static void DestroyMutexOwnerMapEntry(pthread_mutex_t* mutex) { BUTIL_FORCE_INLINE int pthread_mutex_lock_internal(pthread_mutex_t* mutex, const struct timespec* abstime) { int rc = 0; - if (NULL == abstime) { + if (nullptr == abstime) { FIND_SYS_PTHREAD_MUTEX_OWNER_MAP_ENTRY(mutex); SYS_PTHREAD_MUTEX_CHECK_OWNER; rc = sys_pthread_mutex_lock(mutex); @@ -857,7 +857,7 @@ BUTIL_FORCE_INLINE int pthread_mutex_unlock_internal(pthread_mutex_t* mutex) { BUTIL_FORCE_INLINE int pthread_mutex_lock_internal(FastPthreadMutex* mutex, const struct timespec* abstime) { - if (NULL == abstime) { + if (nullptr == abstime) { mutex->lock(); return 0; } else { @@ -891,7 +891,7 @@ BUTIL_FORCE_INLINE int pthread_mutex_lock_impl(Mutex* mutex, const struct timesp // Ask bvar::Collector if this (contended) locking should be sampled const size_t sampling_range = bvar::is_collectable(&g_cp_sl); - bthread_contention_site_t* csite = NULL; + bthread_contention_site_t* csite = nullptr; #ifndef DONT_SPEEDUP_PTHREAD_CONTENTION_PROFILER_WITH_TLS TLSPthreadContentionSites& fast_alt = *BAIDU_GET_PTR_VOLATILE_THREAD_LOCAL(tls_csites); @@ -918,7 +918,7 @@ BUTIL_FORCE_INLINE int pthread_mutex_lock_impl(Mutex* mutex, const struct timesp if (!rc) { // Inside lock if (!csite) { csite = add_pthread_contention_site(mutex); - if (csite == NULL) { + if (csite == nullptr) { return rc; } } @@ -981,7 +981,7 @@ BUTIL_FORCE_INLINE int pthread_mutex_unlock_impl(Mutex* mutex) { #ifndef NO_PTHREAD_MUTEX_HOOK BUTIL_FORCE_INLINE int pthread_mutex_lock_impl(pthread_mutex_t* mutex) { - return internal::pthread_mutex_lock_impl(mutex, NULL); + return internal::pthread_mutex_lock_impl(mutex, nullptr); } BUTIL_FORCE_INLINE int pthread_mutex_trylock_impl(pthread_mutex_t* mutex) { @@ -1022,7 +1022,7 @@ BAIDU_CASSERT(sizeof(unsigned) == sizeof(MutexInternal), #define BTHREAD_MUTEX_SET_OWNER \ do { \ TaskGroup* task_group = BAIDU_GET_VOLATILE_THREAD_LOCAL(tls_task_group); \ - if (NULL != task_group && !task_group->is_current_main_task()) { \ + if (nullptr != task_group && !task_group->is_current_main_task()) { \ m->owner.id = bthread_self(); \ } else { \ m->owner.id = pthread_numeric_id(); \ @@ -1065,7 +1065,7 @@ inline int mutex_lock_contended_impl(bthread_mutex_t* __restrict m, // When a bthread first contends for a lock, active spinning makes sense. // Spin only few times and only if local `rq' is empty. TaskGroup* g = BAIDU_GET_VOLATILE_THREAD_LOCAL(tls_task_group); - if (BAIDU_UNLIKELY(NULL == g || g->rq_size() == 0)) { + if (BAIDU_UNLIKELY(nullptr == g || g->rq_size() == 0)) { for (int i = 0; i < MAX_SPIN_ITER; ++i) { cpu_relax(); } @@ -1107,19 +1107,19 @@ FastPthreadMutex::FastPthreadMutex() : _futex(0) { int FastPthreadMutex::lock_contended(const struct timespec* abstime) { int64_t abstime_us = 0; - if (NULL != abstime) { + if (nullptr != abstime) { abstime_us = butil::timespec_to_microseconds(*abstime); } auto whole = (butil::atomic*)&_futex; while (whole->exchange(BTHREAD_MUTEX_CONTENDED) & BTHREAD_MUTEX_LOCKED) { - timespec* ptimeout = NULL; + timespec* ptimeout = nullptr; timespec timeout{}; - if (NULL != abstime) { + if (nullptr != abstime) { timeout = butil::microseconds_to_timespec( abstime_us - butil::gettimeofday_us()); ptimeout = &timeout; } - if (NULL == abstime || abstime_us > MIN_SLEEP_US) { + if (nullptr == abstime || abstime_us > MIN_SLEEP_US) { if (futex_wait_private(whole, BTHREAD_MUTEX_CONTENDED, ptimeout) < 0 && errno != EWOULDBLOCK && errno != EINTR/*note*/) { // A mutex lock should ignore interruptions in general since @@ -1142,7 +1142,7 @@ void FastPthreadMutex::lock() { } PTHREAD_MUTEX_CHECK_OWNER(_owner); - (void)lock_contended(NULL); + (void)lock_contended(nullptr); } bool FastPthreadMutex::try_lock() { @@ -1177,7 +1177,7 @@ void FastPthreadMutex::unlock() { #endif // BTHREAD_USE_FAST_PTHREAD_MUTEX void FastPthreadMutex::lock() { - internal::pthread_mutex_lock_impl(&_mutex, NULL); + internal::pthread_mutex_lock_impl(&_mutex, nullptr); } void FastPthreadMutex::unlock() { @@ -1203,7 +1203,7 @@ int bthread_mutex_init(bthread_mutex_t* __restrict m, return ENOMEM; } *m->butex = 0; - m->enable_csite = NULL == attr ? true : attr->enable_csite; + m->enable_csite = nullptr == attr ? true : attr->enable_csite; return 0; } @@ -1217,7 +1217,7 @@ int bthread_mutex_trylock(bthread_mutex_t* m) { } int bthread_mutex_lock_contended(bthread_mutex_t* m) { - return bthread::mutex_lock_contended_impl(m, NULL); + return bthread::mutex_lock_contended_impl(m, nullptr); } static int bthread_mutex_lock_impl(bthread_mutex_t* __restrict m, @@ -1253,7 +1253,7 @@ static int bthread_mutex_lock_impl(bthread_mutex_t* __restrict m, } int bthread_mutex_lock(bthread_mutex_t* m) { - return bthread_mutex_lock_impl(m, NULL); + return bthread_mutex_lock_impl(m, nullptr); } int bthread_mutex_timedlock(bthread_mutex_t* __restrict m, diff --git a/src/bthread/mutex.h b/src/bthread/mutex.h index 11c7eae821..ad0c7aa8e9 100644 --- a/src/bthread/mutex.h +++ b/src/bthread/mutex.h @@ -47,7 +47,7 @@ class Mutex { public: typedef bthread_mutex_t* native_handler_type; Mutex() { - int ec = bthread_mutex_init(&_mutex, NULL); + int ec = bthread_mutex_init(&_mutex, nullptr); if (ec != 0) { throw std::system_error(std::error_code(ec, std::system_category()), "Mutex constructor failed"); @@ -127,7 +127,7 @@ template <> class lock_guard { const int rc = bthread_mutex_lock(_pmutex); if (rc) { LOG(FATAL) << "Fail to lock bthread_mutex_t=" << _pmutex << ", " << berror(rc); - _pmutex = NULL; + _pmutex = nullptr; } #else bthread_mutex_lock(_pmutex); @@ -153,7 +153,7 @@ template <> class unique_lock { DISALLOW_COPY_AND_ASSIGN(unique_lock); public: typedef bthread_mutex_t mutex_type; - unique_lock() : _mutex(NULL), _owns_lock(false) {} + unique_lock() : _mutex(nullptr), _owns_lock(false) {} explicit unique_lock(mutex_type& mutex) : _mutex(&mutex), _owns_lock(false) { lock(); @@ -218,7 +218,7 @@ template <> class unique_lock { mutex_type* release() { mutex_type* saved_mutex = _mutex; - _mutex = NULL; + _mutex = nullptr; _owns_lock = false; return saved_mutex; } @@ -239,7 +239,7 @@ namespace bvar { template <> struct MutexConstructor { bool operator()(bthread_mutex_t* mutex) const { - return bthread_mutex_init(mutex, NULL) == 0; + return bthread_mutex_init(mutex, nullptr) == 0; } }; diff --git a/src/bthread/parking_lot.h b/src/bthread/parking_lot.h index bbc9a7c3fd..bd8c2c998c 100644 --- a/src/bthread/parking_lot.h +++ b/src/bthread/parking_lot.h @@ -72,7 +72,7 @@ class BAIDU_CACHELINE_ALIGNMENT ParkingLot { if (_no_signal_when_no_waiter) { _waiter_num.fetch_add(1, butil::memory_order_relaxed); } - futex_wait_private(&_pending_signal, expected_state.val, NULL); + futex_wait_private(&_pending_signal, expected_state.val, nullptr); if (_no_signal_when_no_waiter) { _waiter_num.fetch_sub(1, butil::memory_order_relaxed); } diff --git a/src/bthread/remote_task_queue.h b/src/bthread/remote_task_queue.h index ab05bdde89..98fc522b6a 100644 --- a/src/bthread/remote_task_queue.h +++ b/src/bthread/remote_task_queue.h @@ -40,7 +40,7 @@ class RemoteTaskQueue { int init(size_t cap) { const size_t memsize = sizeof(bthread_t) * cap; void* q_mem = malloc(memsize); - if (q_mem == NULL) { + if (q_mem == nullptr) { return -1; } butil::BoundedQueue q(q_mem, memsize, butil::OWNS_STORAGE); diff --git a/src/bthread/rwlock.cpp b/src/bthread/rwlock.cpp index e28f5ccb8b..92ed9242b4 100644 --- a/src/bthread/rwlock.cpp +++ b/src/bthread/rwlock.cpp @@ -40,7 +40,7 @@ extern void submit_contention(const bthread_contention_site_t& csite, int64_t no #define BTHREAD_RWLOCK_MAYBE_START_SAMPLING \ do { \ if (start_ns == 0) { \ - if (BAIDU_UNLIKELY(g_cp != NULL)) { \ + if (BAIDU_UNLIKELY(g_cp != nullptr)) { \ sampling_range = bvar::is_collectable(&g_cp_sl); \ start_ns = bvar::is_sampling_range_valid(sampling_range) ? \ butil::cpuwide_time_ns() : -1; \ @@ -419,7 +419,7 @@ static int rwlock_unlock(bthread_rwlock_t* rwlock) { // allocations; ownership is `release()'d only on the all-success path. struct ButexDeleter { void operator()(void* butex) const { - if (butex != NULL) { + if (butex != nullptr) { butex_destroy(butex); } } @@ -428,12 +428,12 @@ struct ButexDeleter { static int rwlock_init(bthread_rwlock_t* rwlock) { std::unique_ptr writer_wait_count( butex_create_checked()); - if (writer_wait_count == NULL) { + if (writer_wait_count == nullptr) { LOG(ERROR) << "Fail to create writer_wait_count butex: out of memory"; return ENOMEM; } std::unique_ptr lock_word(butex_create_checked()); - if (lock_word == NULL) { + if (lock_word == nullptr) { LOG(ERROR) << "Fail to create lock_word butex: out of memory"; return ENOMEM; } @@ -469,13 +469,13 @@ static int rwlock_destroy(bthread_rwlock_t* rwlock) { if (rc != 0) { LOG(ERROR) << "Fail to destroy writer_queue_mutex, rc=" << rc; } - if (rwlock->writer_wait_count != NULL) { + if (rwlock->writer_wait_count != nullptr) { butex_destroy(rwlock->writer_wait_count); - rwlock->writer_wait_count = NULL; + rwlock->writer_wait_count = nullptr; } - if (rwlock->lock_word != NULL) { + if (rwlock->lock_word != nullptr) { butex_destroy(rwlock->lock_word); - rwlock->lock_word = NULL; + rwlock->lock_word = nullptr; } return rc; } @@ -494,11 +494,11 @@ int bthread_rwlock_destroy(bthread_rwlock_t* rwlock) { } int bthread_rwlock_rdlock(bthread_rwlock_t* rwlock) { - return bthread::rwlock_rdlock(rwlock, false, NULL); + return bthread::rwlock_rdlock(rwlock, false, nullptr); } int bthread_rwlock_tryrdlock(bthread_rwlock_t* rwlock) { - return bthread::rwlock_rdlock(rwlock, true, NULL); + return bthread::rwlock_rdlock(rwlock, true, nullptr); } int bthread_rwlock_timedrdlock(bthread_rwlock_t* __restrict rwlock, @@ -507,11 +507,11 @@ int bthread_rwlock_timedrdlock(bthread_rwlock_t* __restrict rwlock, } int bthread_rwlock_wrlock(bthread_rwlock_t* rwlock) { - return bthread::rwlock_wrlock(rwlock, false, NULL); + return bthread::rwlock_wrlock(rwlock, false, nullptr); } int bthread_rwlock_trywrlock(bthread_rwlock_t* rwlock) { - return bthread::rwlock_wrlock(rwlock, true, NULL); + return bthread::rwlock_wrlock(rwlock, true, nullptr); } int bthread_rwlock_timedwrlock(bthread_rwlock_t* __restrict rwlock, diff --git a/src/bthread/rwlock.h b/src/bthread/rwlock.h index 295e643f06..25ca5f593f 100644 --- a/src/bthread/rwlock.h +++ b/src/bthread/rwlock.h @@ -33,7 +33,7 @@ class RWLock { typedef bthread_rwlock_t* native_handler_type; RWLock() { - int rc = bthread_rwlock_init(&_rwlock, NULL); + int rc = bthread_rwlock_init(&_rwlock, nullptr); if (rc) { throw std::system_error(std::error_code(rc, std::system_category()), "RWLock constructor failed"); @@ -95,7 +95,7 @@ class RWLockRdGuard { const int rc = bthread_rwlock_rdlock(_rwlock); if (rc) { LOG(FATAL) << "Fail to rdlock bthread_rwlock_t=" << _rwlock << ", " << berror(rc); - _rwlock = NULL; + _rwlock = nullptr; } #else bthread_rwlock_rdlock(_rwlock); @@ -107,7 +107,7 @@ class RWLockRdGuard { ~RWLockRdGuard() { #ifndef NDEBUG - if (NULL != _rwlock) { + if (nullptr != _rwlock) { bthread_rwlock_unlock(_rwlock); } #else @@ -130,7 +130,7 @@ class RWLockWrGuard { const int rc = bthread_rwlock_wrlock(_rwlock); if (rc) { LOG(FATAL) << "Fail to wrlock bthread_rwlock_t=" << _rwlock << ", " << berror(rc); - _rwlock = NULL; + _rwlock = nullptr; } #else bthread_rwlock_wrlock(_rwlock); @@ -142,7 +142,7 @@ class RWLockWrGuard { ~RWLockWrGuard() { #ifndef NDEBUG - if (NULL != _rwlock) { + if (nullptr != _rwlock) { bthread_rwlock_unlock(_rwlock); } #else @@ -174,7 +174,7 @@ class lock_guard { } if (rc) { LOG(FATAL) << "Fail to lock bthread_rwlock_t=" << _rwlock << ", " << berror(rc); - _rwlock = NULL; + _rwlock = nullptr; } #else if (_read) { @@ -187,7 +187,7 @@ class lock_guard { ~lock_guard() { #ifndef NDEBUG - if (NULL != _rwlock) { + if (nullptr != _rwlock) { bthread_rwlock_unlock(_rwlock); } #else diff --git a/src/bthread/semaphore.cpp b/src/bthread/semaphore.cpp index 3813a8a669..7b9c22d555 100644 --- a/src/bthread/semaphore.cpp +++ b/src/bthread/semaphore.cpp @@ -71,7 +71,7 @@ static int bthread_sem_wait_impl(bthread_sem_t* sem, const struct timespec* abst } } // Don't sample when contention profiler is off. - if (NULL != bthread::g_cp && start_ns == 0 && sem->enable_csite && + if (nullptr != bthread::g_cp && start_ns == 0 && sem->enable_csite && !bvar::is_sampling_range_valid(sampling_range)) { // Ask Collector if this (contended) sem waiting should be sampled. sampling_range = bvar::is_collectable(&bthread::g_cp_sl); @@ -112,7 +112,7 @@ static inline int bthread_sem_post(bthread_sem_t* sem, size_t num) { if (num > 0) { unsigned n = ((butil::atomic*)sem->butex) ->fetch_add(num, butil::memory_order_relaxed); - const size_t sampling_range = NULL != bthread::g_cp && sem->enable_csite ? + const size_t sampling_range = nullptr != bthread::g_cp && sem->enable_csite ? bvar::is_collectable(&bthread::g_cp_sl) : bvar::INVALID_SAMPLING_RANGE; const int64_t start_ns = bvar::is_sampling_range_valid(sampling_range) ? butil::cpuwide_time_ns() : -1; @@ -155,7 +155,7 @@ int bthread_sem_trywait(bthread_sem_t* sem) { } int bthread_sem_wait(bthread_sem_t* sem) { - return bthread::bthread_sem_wait_impl(sem, NULL); + return bthread::bthread_sem_wait_impl(sem, nullptr); } int bthread_sem_timedwait(bthread_sem_t* sem, const struct timespec* abstime) { diff --git a/src/bthread/singleton_on_bthread_once.h b/src/bthread/singleton_on_bthread_once.h index 9ea507d788..a914a25ac9 100644 --- a/src/bthread/singleton_on_bthread_once.h +++ b/src/bthread/singleton_on_bthread_once.h @@ -31,7 +31,7 @@ class GetLeakySingleton { }; template -T* GetLeakySingleton::_instance = NULL; +T* GetLeakySingleton::_instance = nullptr; template bthread_once_t* GetLeakySingleton::g_create_leaky_singleton_once diff --git a/src/bthread/stack.cpp b/src/bthread/stack.cpp index 71daf9d7c4..64608cd5eb 100644 --- a/src/bthread/stack.cpp +++ b/src/bthread/stack.cpp @@ -51,7 +51,7 @@ static int64_t get_stack_count(void*) { return s_stack_count.load(butil::memory_order_relaxed); } static bvar::PassiveStatus bvar_stack_count( - "bthread_stack_count", get_stack_count, NULL); + "bthread_stack_count", get_stack_count, nullptr); int allocate_stack_storage(StackStorage* s, int stacksize_in, int guardsize_in) { const static int PAGESIZE = getpagesize(); @@ -66,7 +66,7 @@ int allocate_stack_storage(StackStorage* s, int stacksize_in, int guardsize_in) if (guardsize_in <= 0) { void* mem = malloc(stacksize); - if (NULL == mem) { + if (nullptr == mem) { PLOG_EVERY_SECOND(ERROR) << "Fail to malloc (size=" << stacksize << ")"; return -1; @@ -89,7 +89,7 @@ int allocate_stack_storage(StackStorage* s, int stacksize_in, int guardsize_in) ~PAGESIZE_M1; const int memsize = stacksize + guardsize; - void* const mem = mmap(NULL, memsize, (PROT_READ | PROT_WRITE), + void* const mem = mmap(nullptr, memsize, (PROT_READ | PROT_WRITE), (MAP_PRIVATE | MAP_ANONYMOUS), -1, 0); if (MAP_FAILED == mem) { diff --git a/src/bthread/stack.h b/src/bthread/stack.h index 91d1df6066..d703566e9a 100644 --- a/src/bthread/stack.h +++ b/src/bthread/stack.h @@ -42,7 +42,7 @@ struct StackStorage { void zeroize() { stacksize = 0; guardsize = 0; - bottom = NULL; + bottom = nullptr; valgrind_stack_id = 0; } }; @@ -71,7 +71,7 @@ struct ContextualStack { // Get a stack in the `type' and run `entry' at the first time that the // stack is jumped. ContextualStack* get_stack(StackType type, void (*entry)(intptr_t)); -// Recycle a stack. NULL does nothing. +// Recycle a stack. nullptr does nothing. void return_stack(ContextualStack*); // Jump from stack `from' to stack `to'. `from' must be the stack of callsite // (to save contexts before jumping) diff --git a/src/bthread/stack_inl.h b/src/bthread/stack_inl.h index faa5de07c4..6c313ca361 100644 --- a/src/bthread/stack_inl.h +++ b/src/bthread/stack_inl.h @@ -32,7 +32,7 @@ namespace bthread { namespace internal { BUTIL_FORCE_INLINE void ASanPoisonMemoryRegion(const StackStorage& storage) { - if (NULL == storage.bottom) { + if (nullptr == storage.bottom) { return; } @@ -43,7 +43,7 @@ BUTIL_FORCE_INLINE void ASanPoisonMemoryRegion(const StackStorage& storage) { } BUTIL_FORCE_INLINE void ASanUnpoisonMemoryRegion(const StackStorage& storage) { - if (NULL == storage.bottom) { + if (nullptr == storage.bottom) { return; } CHECK_GT(storage.bottom, @@ -54,7 +54,7 @@ BUTIL_FORCE_INLINE void ASanUnpoisonMemoryRegion(const StackStorage& storage) { BUTIL_FORCE_INLINE void StartSwitchFiber(void** fake_stack_save, StackStorage& storage) { - if (NULL == storage.bottom) { + if (nullptr == storage.bottom) { return; } RELEASE_ASSERT(storage.bottom > @@ -65,7 +65,7 @@ BUTIL_FORCE_INLINE void StartSwitchFiber(void** fake_stack_save, StackStorage& s } BUTIL_FORCE_INLINE void FinishSwitchFiber(void* fake_stack_save) { - BUTIL_ASAN_FINISH_SWITCH_FIBER(fake_stack_save, NULL, NULL); + BUTIL_ASAN_FINISH_SWITCH_FIBER(fake_stack_save, nullptr, nullptr); } class ScopedASanFiberSwitcher { @@ -81,7 +81,7 @@ class ScopedASanFiberSwitcher { DISALLOW_COPY_AND_ASSIGN(ScopedASanFiberSwitcher); private: - void* _fake_stack{NULL}; + void* _fake_stack{nullptr}; }; #define BTHREAD_ASAN_POISON_MEMORY_REGION(storage) \ @@ -127,7 +127,7 @@ template struct StackFactory { if (allocate_stack_storage(&storage, *StackClass::stack_size_flag, FLAGS_guard_page_size) != 0) { storage.zeroize(); - context = NULL; + context = nullptr; return; } context = bthread_make_fcontext(storage.bottom, storage.stacksize, entry); @@ -137,7 +137,7 @@ template struct StackFactory { } ~Wrapper() { if (context) { - context = NULL; + context = nullptr; // Unpoison to avoid affecting other allocator. BTHREAD_ASAN_UNPOISON_MEMORY_REGION(storage); deallocate_stack_storage(&storage); @@ -162,11 +162,8 @@ template struct StackFactory { template <> struct StackFactory { static ContextualStack* get_stack(void (*)(intptr_t)) { - ContextualStack* s = new (std::nothrow) ContextualStack; - if (NULL == s) { - return NULL; - } - s->context = NULL; + ContextualStack* s = new ContextualStack; + s->context = nullptr; s->stacktype = STACK_TYPE_MAIN; s->storage.zeroize(); return s; @@ -180,7 +177,7 @@ template <> struct StackFactory { inline ContextualStack* get_stack(StackType type, void (*entry)(intptr_t)) { switch (type) { case STACK_TYPE_PTHREAD: - return NULL; + return nullptr; case STACK_TYPE_SMALL: return StackFactory::get_stack(entry); case STACK_TYPE_NORMAL: @@ -190,11 +187,11 @@ inline ContextualStack* get_stack(StackType type, void (*entry)(intptr_t)) { case STACK_TYPE_MAIN: return StackFactory::get_stack(entry); } - return NULL; + return nullptr; } inline void return_stack(ContextualStack* s) { - if (NULL == s) { + if (nullptr == s) { return; } switch (s->stacktype) { @@ -257,7 +254,7 @@ template <> struct ObjectPoolValidator< bthread::StackFactory::Wrapper> { inline static bool validate( const bthread::StackFactory::Wrapper* w) { - return w->context != NULL; + return w->context != nullptr; } }; @@ -265,7 +262,7 @@ template <> struct ObjectPoolValidator< bthread::StackFactory::Wrapper> { inline static bool validate( const bthread::StackFactory::Wrapper* w) { - return w->context != NULL; + return w->context != nullptr; } }; @@ -273,7 +270,7 @@ template <> struct ObjectPoolValidator< bthread::StackFactory::Wrapper> { inline static bool validate( const bthread::StackFactory::Wrapper* w) { - return w->context != NULL; + return w->context != nullptr; } }; diff --git a/src/bthread/sys_futex.cpp b/src/bthread/sys_futex.cpp index 803bec6660..010ddcada2 100644 --- a/src/bthread/sys_futex.cpp +++ b/src/bthread/sys_futex.cpp @@ -33,8 +33,8 @@ class SimuFutex { public: SimuFutex() : counts(0) , ref(0) { - pthread_mutex_init(&lock, NULL); - pthread_cond_init(&cond, NULL); + pthread_mutex_init(&lock, nullptr); + pthread_cond_init(&cond, nullptr); } ~SimuFutex() { pthread_mutex_destroy(&lock); @@ -50,14 +50,10 @@ class SimuFutex { static pthread_mutex_t s_futex_map_mutex = PTHREAD_MUTEX_INITIALIZER; static pthread_once_t init_futex_map_once = PTHREAD_ONCE_INIT; -static std::unordered_map* s_futex_map = NULL; +static std::unordered_map* s_futex_map = nullptr; static void InitFutexMap() { // Leave memory to process's clean up. - s_futex_map = new (std::nothrow) std::unordered_map(); - if (NULL == s_futex_map) { - exit(1); - } - return; + s_futex_map = new std::unordered_map(); } int futex_wait_private(void* addr1, int expected, const timespec* timeout) { diff --git a/src/bthread/sys_futex.h b/src/bthread/sys_futex.h index 786d87e097..b19c7eda8f 100644 --- a/src/bthread/sys_futex.h +++ b/src/bthread/sys_futex.h @@ -38,17 +38,17 @@ namespace bthread { inline int futex_wait_private( void* addr1, int expected, const timespec* timeout) { return syscall(SYS_futex, addr1, (FUTEX_WAIT | FUTEX_PRIVATE_FLAG), - expected, timeout, NULL, 0); + expected, timeout, nullptr, 0); } inline int futex_wake_private(void* addr1, int nwake) { return syscall(SYS_futex, addr1, (FUTEX_WAKE | FUTEX_PRIVATE_FLAG), - nwake, NULL, NULL, 0); + nwake, nullptr, nullptr, 0); } inline int futex_requeue_private(void* addr1, int nwake, void* addr2) { return syscall(SYS_futex, addr1, (FUTEX_REQUEUE | FUTEX_PRIVATE_FLAG), - nwake, NULL, addr2, 0); + nwake, nullptr, addr2, 0); } } // namespace bthread diff --git a/src/bthread/task_control.cpp b/src/bthread/task_control.cpp index 3ad3aa508d..5a6bfe831c 100644 --- a/src/bthread/task_control.cpp +++ b/src/bthread/task_control.cpp @@ -71,8 +71,8 @@ DECLARE_int32(bthread_parking_lot_of_each_tag); extern pthread_mutex_t g_task_control_mutex; EXTERN_BAIDU_VOLATILE_THREAD_LOCAL(TaskGroup*, tls_task_group); -void (*g_worker_startfn)() = NULL; -void (*g_tagged_worker_startfn)(bthread_tag_t) = NULL; +void (*g_worker_startfn)() = nullptr; +void (*g_tagged_worker_startfn)(bthread_tag_t) = nullptr; // May be called in other modules to run startfn in non-worker pthreads. void run_worker_startfn() { @@ -107,9 +107,9 @@ void* TaskControl::worker_thread(void* arg) { TaskGroup* g = c->create_group(tag); TaskStatistics stat; - if (NULL == g) { + if (nullptr == g) { LOG(ERROR) << "Fail to create TaskGroup in pthread=" << pthread_self(); - return NULL; + return nullptr; } g->_tid = pthread_self(); @@ -138,27 +138,23 @@ void* TaskControl::worker_thread(void* arg) { BT_VLOG << "Destroying worker=" << pthread_self() << " bthread=" << g->main_tid() << " idle=" << stat.cputime_ns / 1000000.0 << "ms uptime=" << g->current_uptime_ns() / 1000000.0 << "ms"; - BAIDU_SET_VOLATILE_THREAD_LOCAL(tls_task_group, NULL); + BAIDU_SET_VOLATILE_THREAD_LOCAL(tls_task_group, nullptr); g->destroy_self(); c->_nworkers << -1; c->tag_nworkers(g->tag()) << -1; - return NULL; + return nullptr; } TaskGroup* TaskControl::create_group(bthread_tag_t tag) { - TaskGroup* g = new (std::nothrow) TaskGroup(this); - if (NULL == g) { - LOG(FATAL) << "Fail to new TaskGroup"; - return NULL; - } + TaskGroup* g = new TaskGroup(this); if (g->init(FLAGS_task_group_runqueue_capacity) != 0) { LOG(ERROR) << "Fail to init TaskGroup"; delete g; - return NULL; + return nullptr; } if (_add_group(g, tag) != 0) { delete g; - return NULL; + return nullptr; } return g; } @@ -201,7 +197,7 @@ TaskControl::TaskControl() , _stop(false) , _concurrency(0) , _nworkers("bthread_worker_count") - , _pending_time(NULL) + , _pending_time(nullptr) // Delay exposure of following two vars because they rely on TC which // is not initialized yet. , _cumulated_worker_time(get_cumulated_worker_time_from_this, this) @@ -275,7 +271,7 @@ int TaskControl::init(int concurrency) { } // Make sure TimerThread is ready. - if (get_or_create_global_timer_thread() == NULL) { + if (get_or_create_global_timer_thread() == nullptr) { LOG(ERROR) << "Fail to get global_timer_thread"; return -1; } @@ -290,7 +286,7 @@ int TaskControl::init(int concurrency) { _workers.resize(_concurrency); for (int i = 0; i < _concurrency; ++i) { auto arg = new WorkerThreadArgs(this, i % FLAGS_task_group_ntags); - const int rc = pthread_create(&_workers[i], NULL, worker_thread, arg); + const int rc = pthread_create(&_workers[i], nullptr, worker_thread, arg); if (rc) { delete arg; PLOG(ERROR) << "Fail to create _workers[" << i << "]"; @@ -303,7 +299,7 @@ int TaskControl::init(int concurrency) { _status.expose("bthread_group_status"); // Wait for at least one group is added so that choose_one_group() - // never returns NULL. + // never returns nullptr. // TODO: Handle the case that worker quits before add_group for (int i = 0; i < FLAGS_task_group_ntags;) { if (_tagged_ngroup[i].load(std::memory_order_acquire) == 0) { @@ -334,7 +330,7 @@ int TaskControl::add_workers(int num, bthread_tag_t tag) { _concurrency.fetch_add(1); auto arg = new WorkerThreadArgs(this, tag); const int rc = pthread_create( - &_workers[i + old_concurency], NULL, worker_thread, arg); + &_workers[i + old_concurency], nullptr, worker_thread, arg); if (rc) { delete arg; PLOG(WARNING) << "Fail to create _workers[" << i + old_concurency << "]"; @@ -355,7 +351,7 @@ TaskGroup* TaskControl::choose_one_group(bthread_tag_t tag) { return groups[butil::fast_rand_less_than(ngroup)]; } CHECK(false) << "Impossible: ngroup is 0"; - return NULL; + return nullptr; } // Parse a single cpu-range-list such as "0-3,5,7" into a sorted, deduplicated @@ -526,14 +522,14 @@ void TaskControl::stop_and_join() { } // Join workers for (auto worker : _workers) { - pthread_join(worker, NULL); + pthread_join(worker, nullptr); } } TaskControl::~TaskControl() { // NOTE: g_task_control is not destructed now because the situation // is extremely racy. - delete _pending_time.exchange(NULL, butil::memory_order_relaxed); + delete _pending_time.exchange(nullptr, butil::memory_order_relaxed); _worker_usage_second.hide(); _switch_per_second.hide(); _signal_per_second.hide(); @@ -543,7 +539,7 @@ TaskControl::~TaskControl() { } int TaskControl::_add_group(TaskGroup* g, bthread_tag_t tag) { - if (__builtin_expect(NULL == g, 0)) { + if (__builtin_expect(nullptr == g, 0)) { return -1; } std::unique_lock mu(_modify_group_mutex); @@ -569,7 +565,7 @@ void TaskControl::delete_task_group(void* arg) { } int TaskControl::_destroy_group(TaskGroup* g) { - if (NULL == g) { + if (nullptr == g) { LOG(ERROR) << "Param[g] is NULL"; return -1; } @@ -598,7 +594,7 @@ int TaskControl::_destroy_group(TaskGroup* g) { // we think the pending tasks of _groups[ngroup - 1] would // not miss. tag_ngroup(tag).store(ngroup - 1, butil::memory_order_release); - //_groups[ngroup - 1] = NULL; + //_groups[ngroup - 1] = nullptr; erased = true; break; } @@ -643,7 +639,7 @@ bool TaskControl::steal_task(bthread_t* tid, size_t* seed, size_t offset) { auto& groups = tag_group(tag); for (size_t i = 0; i < ngroup; ++i, s += offset) { TaskGroup* g = groups[s % ngroup]; - // g is possibly NULL because of concurrent _destroy_group + // g is possibly nullptr because of concurrent _destroy_group if (g) { if (g->_rq.steal(tid)) { stolen = true; diff --git a/src/bthread/task_control.h b/src/bthread/task_control.h index 1dd3dfc107..8cc8c4ba4e 100644 --- a/src/bthread/task_control.h +++ b/src/bthread/task_control.h @@ -88,7 +88,7 @@ friend bthread_t init_for_pthread_stack_trace(); int add_workers(int num, bthread_tag_t tag); // Choose one TaskGroup (randomly right now). - // If this method is called after init(), it never returns NULL. + // If this method is called after init(), it never returns nullptr. TaskGroup* choose_one_group(bthread_tag_t tag); // Parse FLAGS_cpu_set into _tag_cpus. Two formats are accepted: diff --git a/src/bthread/task_group.cpp b/src/bthread/task_group.cpp index 777d7514a3..679e52ef5f 100644 --- a/src/bthread/task_group.cpp +++ b/src/bthread/task_group.cpp @@ -50,12 +50,12 @@ namespace bthread { // Global span function pointers for bthread lifecycle tracing. // These are set by brpc layer via bthread_set_span_funcs(). -void* (*g_create_bthread_span)() = NULL; -void (*g_rpcz_parent_span_dtor)(void*) = NULL; -void (*g_end_bthread_span)() = NULL; +void* (*g_create_bthread_span)() = nullptr; +void (*g_rpcz_parent_span_dtor)(void*) = nullptr; +void (*g_end_bthread_span)() = nullptr; static const bthread_attr_t BTHREAD_ATTR_TASKGROUP = { - BTHREAD_STACKTYPE_UNKNOWN, 0, NULL, BTHREAD_TAG_INVALID, {0} }; + BTHREAD_STACKTYPE_UNKNOWN, 0, nullptr, BTHREAD_TAG_INVALID, {0} }; DEFINE_bool(show_bthread_creation_in_vars, false, "When this flags is on, The time " "from bthread creation to first run will be recorded and shown in /vars"); @@ -69,7 +69,7 @@ DEFINE_bool(bthread_enable_cpu_clock_stat, false, "Enable CPU clock statistics for bthread"); BUTIL_VALIDATE_GFLAG(bthread_enable_cpu_clock_stat, butil::PassValidate); -BAIDU_VOLATILE_THREAD_LOCAL(TaskGroup*, tls_task_group, NULL); +BAIDU_VOLATILE_THREAD_LOCAL(TaskGroup*, tls_task_group, nullptr); // Sync with TaskMeta::local_storage when a bthread is created or destroyed. // During running, the two fields may be inconsistent, use tls_bls as the // groundtruth. @@ -80,7 +80,7 @@ extern void return_keytable(bthread_keytable_pool_t*, KeyTable*); // [Hacky] This is a special TLS set by bthread-rpc privately... to save // overhead of creation keytable, may be removed later. -BAIDU_VOLATILE_THREAD_LOCAL(void*, tls_unique_user_ptr, NULL); +BAIDU_VOLATILE_THREAD_LOCAL(void*, tls_unique_user_ptr, nullptr); const TaskStatistics EMPTY_STAT = { 0, 0, 0 }; @@ -183,7 +183,7 @@ void AtomicInteger128::store(Value value) { int TaskGroup::get_attr(bthread_t tid, bthread_attr_t* out) { TaskMeta* const m = address_meta(tid); - if (m != NULL) { + if (m != nullptr) { const uint32_t given_ver = get_version(tid); BAIDU_SCOPED_LOCK(m->version_lock); if (given_ver == *m->version_butex) { @@ -197,7 +197,7 @@ int TaskGroup::get_attr(bthread_t tid, bthread_attr_t* out) { void TaskGroup::set_stopped(bthread_t tid) { TaskMeta* const m = address_meta(tid); - if (m != NULL) { + if (m != nullptr) { const uint32_t given_ver = get_version(tid); BAIDU_SCOPED_LOCK(m->version_lock); if (given_ver == *m->version_butex) { @@ -208,7 +208,7 @@ void TaskGroup::set_stopped(bthread_t tid) { bool TaskGroup::is_stopped(bthread_t tid) { TaskMeta* const m = address_meta(tid); - if (m != NULL) { + if (m != nullptr) { const uint32_t given_ver = get_version(tid); BAIDU_SCOPED_LOCK(m->version_lock); if (given_ver == *m->version_butex) { @@ -299,7 +299,7 @@ TaskGroup::~TaskGroup() { TaskMeta* m = address_meta(_main_tid); CHECK(_main_stack == m->stack); #ifdef BUTIL_USE_ASAN - _main_stack->storage.bottom = NULL; + _main_stack->storage.bottom = nullptr; _main_stack->storage.stacksize = 0; #endif // BUTIL_USE_ASAN return_stack(m->release_stack()); @@ -327,7 +327,7 @@ int PthreadAttrGetStack(void*& stack_addr, size_t& stack_size) { LOG(ERROR) << "Fail to get pthread attributes: " << berror(rc); return rc; } - void* stack_lowest = NULL; + void* stack_lowest = nullptr; rc = pthread_attr_getstack(&attr, &stack_lowest, &stack_size); if (0 != rc) { LOG(ERROR) << "Fail to get pthread stack: " << berror(rc); @@ -352,21 +352,21 @@ int TaskGroup::init(size_t runqueue_capacity) { } #ifdef BUTIL_USE_ASAN - void* stack_addr = NULL; + void* stack_addr = nullptr; size_t stack_size = 0; if (0 != PthreadAttrGetStack(stack_addr, stack_size)) { return -1; } #endif // BUTIL_USE_ASAN - ContextualStack* stk = get_stack(STACK_TYPE_MAIN, NULL); - if (NULL == stk) { + ContextualStack* stk = get_stack(STACK_TYPE_MAIN, nullptr); + if (nullptr == stk) { LOG(FATAL) << "Fail to get main stack container"; return -1; } butil::ResourceId slot; TaskMeta* m = butil::get_resource(&slot); - if (NULL == m) { + if (nullptr == m) { LOG(FATAL) << "Fail to get TaskMeta"; return -1; } @@ -374,8 +374,8 @@ int TaskGroup::init(size_t runqueue_capacity) { m->stop = false; m->interrupted = false; m->about_to_quit = false; - m->fn = NULL; - m->arg = NULL; + m->fn = nullptr; + m->arg = nullptr; m->local_storage = LOCAL_STORAGE_INIT; m->cpuwide_start_ns = butil::cpuwide_time_ns(); m->stat = EMPTY_STAT; @@ -404,8 +404,8 @@ int TaskGroup::init(size_t runqueue_capacity) { #ifdef BUTIL_USE_ASAN void TaskGroup::asan_task_runner(intptr_t) { // This is a new thread, and it doesn't have the fake stack yet. ASan will - // create it lazily, for now just pass NULL. - internal::FinishSwitchFiber(NULL); + // create it lazily, for now just pass nullptr. + internal::FinishSwitchFiber(nullptr); task_runner(0); } #endif // BUTIL_USE_ASAN @@ -421,7 +421,7 @@ void TaskGroup::task_runner(intptr_t skip_remained) { if (!skip_remained) { while (g->_last_context_remained) { RemainedFn fn = g->_last_context_remained; - g->_last_context_remained = NULL; + g->_last_context_remained = nullptr; fn(g->_last_context_remained_arg); g = BAIDU_GET_VOLATILE_THREAD_LOCAL(tls_task_group); } @@ -488,20 +488,20 @@ void TaskGroup::task_runner(intptr_t skip_remained) { if (tls_bls_ptr->rpcz_parent_span && g_rpcz_parent_span_dtor) { g_rpcz_parent_span_dtor(tls_bls_ptr->rpcz_parent_span); tls_bls_ptr = bthread::tls_bls_ptr(); - tls_bls_ptr->rpcz_parent_span = NULL; - m->local_storage.rpcz_parent_span = NULL; + tls_bls_ptr->rpcz_parent_span = nullptr; + m->local_storage.rpcz_parent_span = nullptr; } // Clean tls variables, must be done before changing version_butex // otherwise another thread just joined this thread may not see side // effects of destructing tls variables. KeyTable* kt = tls_bls_ptr->keytable; - if (kt != NULL) { + if (kt != nullptr) { return_keytable(m->attr.keytable_pool, kt); // After deletion: tls may be set during deletion. tls_bls_ptr = bthread::tls_bls_ptr(); - tls_bls_ptr->keytable = NULL; - m->local_storage.keytable = NULL; // optional + tls_bls_ptr->keytable = nullptr; + m->local_storage.keytable = nullptr; // optional } // During running the function in TaskMeta and deleting the KeyTable in @@ -548,10 +548,10 @@ void TaskGroup::task_runner(intptr_t skip_remained) { void TaskGroup::_release_last_context(void* arg) { TaskMeta* m = static_cast(arg); if (m->stack_type() != STACK_TYPE_PTHREAD) { - return_stack(m->release_stack()/*may be NULL*/); + return_stack(m->release_stack()/*may be nullptr*/); } else { // it's _main_stack, don't return. - m->set_stack(NULL); + m->set_stack(nullptr); } return_resource(get_slot(m->tid)); } @@ -568,17 +568,17 @@ int TaskGroup::start_foreground(TaskGroup** pg, const bthread_attr_t using_attr = (attr ? *attr : BTHREAD_ATTR_NORMAL); butil::ResourceId slot; TaskMeta* m = butil::get_resource(&slot); - if (BAIDU_UNLIKELY(NULL == m)) { + if (BAIDU_UNLIKELY(nullptr == m)) { return ENOMEM; } - CHECK(m->current_waiter.load(butil::memory_order_relaxed) == NULL); + CHECK(m->current_waiter.load(butil::memory_order_relaxed) == nullptr); m->sleep_failed = false; m->stop = false; m->interrupted = false; m->about_to_quit = false; m->fn = fn; m->arg = arg; - CHECK(m->stack == NULL); + CHECK(m->stack == nullptr); m->attr = using_attr; m->local_storage = LOCAL_STORAGE_INIT; if (using_attr.flags & BTHREAD_INHERIT_SPAN) { @@ -610,7 +610,7 @@ int TaskGroup::start_foreground(TaskGroup** pg, g->ready_to_run(m, using_attr.flags & BTHREAD_NOSIGNAL); } else { // NOSIGNAL affects current task, not the new task. - RemainedFn fn = NULL; + RemainedFn fn = nullptr; auto& cur_attr = g->_cur_meta->attr; if (g->_control->_enable_priority_queue && cur_attr.flags & BTHREAD_GLOBAL_PRIORITY) { fn = priority_to_run; @@ -640,17 +640,17 @@ int TaskGroup::start_background(bthread_t* __restrict th, const bthread_attr_t using_attr = (attr ? *attr : BTHREAD_ATTR_NORMAL); butil::ResourceId slot; TaskMeta* m = butil::get_resource(&slot); - if (BAIDU_UNLIKELY(NULL == m)) { + if (BAIDU_UNLIKELY(nullptr == m)) { return ENOMEM; } - CHECK(m->current_waiter.load(butil::memory_order_relaxed) == NULL); + CHECK(m->current_waiter.load(butil::memory_order_relaxed) == nullptr); m->sleep_failed = false; m->stop = false; m->interrupted = false; m->about_to_quit = false; m->fn = fn; m->arg = arg; - CHECK(m->stack == NULL); + CHECK(m->stack == nullptr); m->attr = using_attr; m->local_storage = LOCAL_STORAGE_INIT; if (using_attr.flags & BTHREAD_INHERIT_SPAN) { @@ -699,18 +699,18 @@ int TaskGroup::join(bthread_t tid, void** return_value) { return EINVAL; } TaskMeta* m = address_meta(tid); - if (BAIDU_UNLIKELY(NULL == m)) { + if (BAIDU_UNLIKELY(nullptr == m)) { // The bthread is not created yet, this join is definitely wrong. return EINVAL; } TaskGroup* g = BAIDU_GET_VOLATILE_THREAD_LOCAL(tls_task_group); - if (g != NULL && g->current_tid() == tid) { + if (g != nullptr && g->current_tid() == tid) { // joining self causes indefinite waiting. return EINVAL; } const uint32_t expected_version = get_version(tid); while (*m->version_butex == expected_version) { - if (butex_wait(m->version_butex, expected_version, NULL) < 0 && + if (butex_wait(m->version_butex, expected_version, nullptr) < 0 && errno != EWOULDBLOCK && errno != EINTR) { return errno; } @@ -720,7 +720,7 @@ int TaskGroup::join(bthread_t tid, void** return_value) { // guarantee provided by pthread_join() across supported architectures. butil::atomic_thread_fence(butil::memory_order_acquire); if (return_value) { - *return_value = NULL; + *return_value = nullptr; } return 0; } @@ -728,7 +728,7 @@ int TaskGroup::join(bthread_t tid, void** return_value) { bool TaskGroup::exists(bthread_t tid) { if (tid != 0) { // tid of bthread is never 0. TaskMeta* m = address_meta(tid); - if (m != NULL) { + if (m != nullptr) { return (*m->version_butex == get_version(tid)); } } @@ -760,7 +760,7 @@ void TaskGroup::ending_sched(TaskGroup** pg) { TaskMeta* const cur_meta = g->_cur_meta; TaskMeta* next_meta = address_meta(next_tid); - if (next_meta->stack == NULL) { + if (next_meta->stack == nullptr) { if (next_meta->stack_type() == cur_meta->stack_type()) { // Reuse the stack of the current ending task. // @@ -856,7 +856,7 @@ void TaskGroup::sched_to(TaskGroup** pg, TaskMeta* next_meta) { << next_meta->tid; } - if (cur_meta->stack != NULL) { + if (cur_meta->stack != nullptr) { if (next_meta->stack != cur_meta->stack) { CheckBthreadScheSafety(); #ifdef BRPC_BTHREAD_TRACER @@ -893,7 +893,7 @@ void TaskGroup::sched_to(TaskGroup** pg, TaskMeta* next_meta) { while (g->_last_context_remained) { RemainedFn fn = g->_last_context_remained; - g->_last_context_remained = NULL; + g->_last_context_remained = nullptr; fn(g->_last_context_remained_arg); g = BAIDU_GET_VOLATILE_THREAD_LOCAL(tls_task_group); } @@ -912,7 +912,7 @@ void TaskGroup::sched_to(TaskGroup** pg, TaskMeta* next_meta) { void TaskGroup::destroy_self() { if (_control) { _control->_destroy_group(this); - _control = NULL; + _control = nullptr; } else { CHECK(false); } @@ -1033,7 +1033,7 @@ struct SleepArgs { }; static void ready_to_run_from_timer_thread(void* arg) { - CHECK(BAIDU_GET_VOLATILE_THREAD_LOCAL(tls_task_group) == NULL); + CHECK(BAIDU_GET_VOLATILE_THREAD_LOCAL(tls_task_group) == nullptr); const SleepArgs* e = static_cast(arg); TaskGroup* g = e->group; bthread_tag_t tag = g->tag(); @@ -1126,13 +1126,13 @@ bool erase_from_butex_because_of_interruption(ButexWaiter* bw); static int interrupt_and_consume_waiters( bthread_t tid, ButexWaiter** pw, uint64_t* sleep_id) { TaskMeta* const m = TaskGroup::address_meta(tid); - if (m == NULL) { + if (m == nullptr) { return EINVAL; } const uint32_t given_ver = get_version(tid); BAIDU_SCOPED_LOCK(m->version_lock); if (given_ver == *m->version_butex) { - *pw = m->current_waiter.exchange(NULL, butil::memory_order_acquire); + *pw = m->current_waiter.exchange(nullptr, butil::memory_order_acquire); *sleep_id = m->current_sleep; m->current_sleep = 0; // only one stopper gets the sleep_id m->interrupted = true; @@ -1143,7 +1143,7 @@ static int interrupt_and_consume_waiters( static int set_butex_waiter(bthread_t tid, ButexWaiter* w) { TaskMeta* const m = TaskGroup::address_meta(tid); - if (m != NULL) { + if (m != nullptr) { const uint32_t given_ver = get_version(tid); BAIDU_SCOPED_LOCK(m->version_lock); if (given_ver == *m->version_butex) { @@ -1164,7 +1164,7 @@ static int set_butex_waiter(bthread_t tid, ButexWaiter* w) { // can't be interrupted. int TaskGroup::interrupt(bthread_t tid, TaskControl* c) { // Consume current_waiter in the TaskMeta, wake it up then set it back. - ButexWaiter* w = NULL; + ButexWaiter* w = nullptr; uint64_t sleep_id = 0; int rc = interrupt_and_consume_waiters(tid, &w, &sleep_id); if (rc) { @@ -1172,10 +1172,10 @@ int TaskGroup::interrupt(bthread_t tid, TaskControl* c) { } // a bthread cannot wait on a butex and be sleepy at the same time. CHECK(!sleep_id || !w); - if (w != NULL) { + if (w != nullptr) { erase_from_butex_because_of_interruption(w); // If butex_wait() already wakes up before we set current_waiter back, - // the function will spin until current_waiter becomes non-NULL. + // the function will spin until current_waiter becomes non-nullptr. rc = set_butex_waiter(tid, w); if (rc) { LOG(FATAL) << "butex_wait should spin until setting back waiter"; @@ -1208,7 +1208,7 @@ void TaskGroup::yield(TaskGroup** pg) { void print_task(std::ostream& os, bthread_t tid, bool enable_trace, bool ignore_not_matched = false) { TaskMeta* const m = TaskGroup::address_meta(tid); - if (m == NULL) { + if (m == nullptr) { os << "bthread=" << tid << " : never existed\n"; return; } @@ -1217,8 +1217,8 @@ void print_task(std::ostream& os, bthread_t tid, bool enable_trace, bool stop = false; bool interrupted = false; bool about_to_quit = false; - void* (*fn)(void*) = NULL; - void* arg = NULL; + void* (*fn)(void*) = nullptr; + void* arg = nullptr; bthread_attr_t attr = BTHREAD_ATTR_NORMAL; bool has_tls = false; int64_t cpuwide_start_ns = 0; diff --git a/src/bthread/task_group.h b/src/bthread/task_group.h index c21e06ba39..f48e02f5e9 100644 --- a/src/bthread/task_group.h +++ b/src/bthread/task_group.h @@ -128,7 +128,7 @@ class TaskGroup { // Suspend caller for at least |timeout_us| microseconds. // If |timeout_us| is 0, this function does nothing. - // If |group| is NULL or current thread is non-bthread, call usleep(3) + // If |group| is nullptr or current thread is non-bthread, call usleep(3) // instead. This function does not create thread-local TaskGroup. // Returns: 0 on success, -1 otherwise and errno is set. static int usleep(TaskGroup** pg, uint64_t timeout_us); @@ -348,10 +348,10 @@ friend class TaskControl; return g->_main_tid == tid; } - TaskMeta* _cur_meta{NULL}; + TaskMeta* _cur_meta{nullptr}; // the control that this group belongs to - TaskControl* _control{NULL}; + TaskControl* _control{nullptr}; int _num_nosignal{0}; int _nsignaled{0}; AtomicCPUTimeStat _cpu_time_stat; @@ -359,16 +359,16 @@ friend class TaskControl; int64_t _last_cpu_clock_ns{0}; size_t _nswitch{0}; - RemainedFn _last_context_remained{NULL}; - void* _last_context_remained_arg{NULL}; + RemainedFn _last_context_remained{nullptr}; + void* _last_context_remained_arg{nullptr}; - ParkingLot* _pl{NULL}; + ParkingLot* _pl{nullptr}; #ifndef BTHREAD_DONT_SAVE_PARKING_STATE ParkingLot::State _last_pl_state; #endif size_t _steal_seed{butil::fast_rand()}; size_t _steal_offset{prime_offset(_steal_seed)}; - ContextualStack* _main_stack{NULL}; + ContextualStack* _main_stack{nullptr}; bthread_t _main_tid{INVALID_BTHREAD}; WorkStealingQueue _rq; RemoteTaskQueue _remote_rq; diff --git a/src/bthread/task_group_inl.h b/src/bthread/task_group_inl.h index faa5683b6c..c0709286ba 100644 --- a/src/bthread/task_group_inl.h +++ b/src/bthread/task_group_inl.h @@ -39,10 +39,10 @@ inline uint32_t get_version(bthread_t tid) { inline TaskMeta* TaskGroup::address_meta(bthread_t tid) { // TaskMeta * m = address_resource(get_slot(tid)); - // if (m != NULL && m->version == get_version(tid)) { + // if (m != nullptr && m->version == get_version(tid)) { // return m; // } - // return NULL; + // return nullptr; return address_resource(get_slot(tid)); } @@ -61,7 +61,7 @@ inline void TaskGroup::exchange(TaskGroup** pg, TaskMeta* next_meta) { inline void TaskGroup::sched_to(TaskGroup** pg, bthread_t next_tid) { TaskMeta* next_meta = address_meta(next_tid); - if (next_meta->stack == NULL) { + if (next_meta->stack == nullptr) { #ifdef BUTIL_USE_ASAN ContextualStack* stk = get_stack(next_meta->stack_type(), asan_task_runner); #else diff --git a/src/bthread/task_meta.h b/src/bthread/task_meta.h index 7c9e63790e..2dae2fea27 100644 --- a/src/bthread/task_meta.h +++ b/src/bthread/task_meta.h @@ -47,7 +47,7 @@ struct LocalStorage { void* rpcz_parent_span; // Points to std::weak_ptr* (managed by brpc) }; -#define BTHREAD_LOCAL_STORAGE_INITIALIZER { NULL, NULL, NULL } +#define BTHREAD_LOCAL_STORAGE_INITIALIZER { nullptr, nullptr, nullptr } const static LocalStorage LOCAL_STORAGE_INIT = BTHREAD_LOCAL_STORAGE_INITIALIZER; @@ -70,7 +70,7 @@ enum TaskStatus { struct TaskMeta { // [Not Reset] - butil::atomic current_waiter{NULL}; + butil::atomic current_waiter{nullptr}; uint64_t current_sleep{TimerThread::INVALID_TASK_ID}; // A flag to mark if the Timer scheduling failed. @@ -89,7 +89,7 @@ struct TaskMeta { pthread_spinlock_t version_lock{}; // [Not Reset] only modified by one bthread at any time, no need to be atomic - uint32_t* version_butex{NULL}; + uint32_t* version_butex{nullptr}; // The identifier. It does not have to be here, however many code is // simplified if they can get tid from TaskMeta. @@ -98,11 +98,11 @@ struct TaskMeta { int priority_index{-1}; // User function and argument - void* (*fn)(void*){NULL}; - void* arg{NULL}; + void* (*fn)(void*){nullptr}; + void* arg{nullptr}; // Stack of this task. - ContextualStack* stack{NULL}; + ContextualStack* stack{nullptr}; // Attributes creating this task bthread_attr_t attr{BTHREAD_ATTR_NORMAL}; @@ -133,13 +133,13 @@ struct TaskMeta { pthread_spin_init(&version_lock, 0); version_butex = butex_create_checked(); *version_butex = 1; - pthread_mutex_init(&trace_lock, NULL); + pthread_mutex_init(&trace_lock, nullptr); } ~TaskMeta() { pthread_mutex_destroy(&trace_lock); butex_destroy(version_butex); - version_butex = NULL; + version_butex = nullptr; pthread_spin_destroy(&version_lock); } @@ -149,7 +149,7 @@ struct TaskMeta { ContextualStack* release_stack() { ContextualStack* tmp = stack; - stack = NULL; + stack = nullptr; return tmp; } @@ -162,7 +162,7 @@ struct TaskMeta { // This is set by brpc layer. When a bthread is created with BTHREAD_INHERIT_SPAN, // this callback is invoked to create a new span for the bthread. // The returned void* points to a heap-allocated weak_ptr* managed by brpc layer. -// Returns NULL if span creation is disabled or fails. +// Returns nullptr if span creation is disabled or fails. extern void* (*g_create_bthread_span)(); // Global destructor callback for rpcz_parent_span. diff --git a/src/bthread/task_tracer.cpp b/src/bthread/task_tracer.cpp index e6049f0ded..1cc5c05a2e 100644 --- a/src/bthread/task_tracer.cpp +++ b/src/bthread/task_tracer.cpp @@ -157,7 +157,7 @@ void TaskTracer::set_status(TaskStatus s, TaskMeta* m) { tracing = m->traced; // bthread is scheduled for the first time. - if (TASK_STATUS_READY == s && NULL == m->stack) { + if (TASK_STATUS_READY == s && nullptr == m->stack) { m->status = TASK_STATUS_FIRST_READY; } else { m->status = s; @@ -205,7 +205,7 @@ TaskTracer::Result TaskTracer::TraceImpl(bthread_t tid) { }; if (tid == bthread_self() || - (NULL != pthread_fake_meta && tid == pthread_fake_meta->tid)) { + (nullptr != pthread_fake_meta && tid == pthread_fake_meta->tid)) { return Result::MakeErrorResult("Forbid to trace self=%d", tid); } @@ -221,7 +221,7 @@ TaskTracer::Result TaskTracer::TraceImpl(bthread_t tid) { _inuse_signal_syncs.erase(iter, _inuse_signal_syncs.end()); TaskMeta* m = TaskGroup::address_meta(tid); - if (NULL == m) { + if (nullptr == m) { return Result::MakeErrorResult("bthread=%d never existed", tid); } @@ -335,7 +335,7 @@ bool TaskTracer::RegisterSignalHandler() { PLOG(ERROR) << "Failed to sigaction"; return false; } - if (NULL != old_sa.sa_handler || NULL != old_sa.sa_sigaction) { + if (nullptr != old_sa.sa_handler || nullptr != old_sa.sa_sigaction) { LOG(ERROR) << "Signal handler of signal number " << _signal_num << " is already registered"; return false; @@ -350,14 +350,15 @@ void TaskTracer::SignalHandler(int, siginfo_t* info, void* context) { // Ref has been taken before the signal is sent, so no need to add ref here. butil::intrusive_ptr signal_sync( static_cast(info->si_value.sival_ptr), false); - if (NULL == signal_sync) { + if (nullptr == signal_sync) { // The signal is not from Tracer, such as TaskControl, do nothing. return; } // Skip the first frame, which is the signal handler itself. - signal_sync->result.frame_count = absl::DefaultStackUnwinder(signal_sync->result.ips, NULL, - arraysize(signal_sync->result.ips), 1, - context, NULL); + signal_sync->result.frame_count = + absl::DefaultStackUnwinder(signal_sync->result.ips, nullptr, + arraysize(signal_sync->result.ips), + 1, context, nullptr); // write() is async-signal-safe. // Don't care about the return value. butil::ignore_result(write(signal_sync->pipe_fds[1], "1", 1)); diff --git a/src/bthread/timer_thread.cpp b/src/bthread/timer_thread.cpp index 1280e3e755..b0a5b9f061 100644 --- a/src/bthread/timer_thread.cpp +++ b/src/bthread/timer_thread.cpp @@ -100,7 +100,7 @@ class BAIDU_CACHELINE_ALIGNMENT TimerThread::Bucket { public: Bucket() : _nearest_run_time(std::numeric_limits::max()) - , _task_head(NULL) { + , _task_head(nullptr) { } ~Bucket() {} @@ -148,13 +148,13 @@ inline bool task_greater(const TimerThread::Task* a, const TimerThread::Task* b) void* TimerThread::run_this(void* arg) { butil::PlatformThread::SetNameSimple("brpc_timer"); static_cast(arg)->run(); - return NULL; + return nullptr; } TimerThread::TimerThread() : _started(false) , _stop(false) - , _buckets(NULL) + , _buckets(nullptr) , _nearest_run_time(std::numeric_limits::max()) , _nsignals(0) , _npending(0) @@ -164,7 +164,7 @@ TimerThread::TimerThread() TimerThread::~TimerThread() { stop_and_join(); delete [] _buckets; - _buckets = NULL; + _buckets = nullptr; } int TimerThread::start(const TimerThreadOptions* options_in) { @@ -182,12 +182,8 @@ int TimerThread::start(const TimerThreadOptions* options_in) { LOG(ERROR) << "num_buckets=" << _options.num_buckets << " is too big"; return EINVAL; } - _buckets = new (std::nothrow) Bucket[_options.num_buckets]; - if (NULL == _buckets) { - LOG(ERROR) << "Fail to new _buckets"; - return ENOMEM; - } - const int ret = pthread_create(&_thread, NULL, TimerThread::run_this, this); + _buckets = new Bucket[_options.num_buckets]; + const int ret = pthread_create(&_thread, nullptr, TimerThread::run_this, this); if (ret) { return ret; } @@ -196,7 +192,7 @@ int TimerThread::start(const TimerThreadOptions* options_in) { } TimerThread::Task* TimerThread::Bucket::consume_tasks() { - Task* head = NULL; + Task* head = nullptr; if (_task_head) { // NOTE: schedule() and consume_tasks() are sequenced // by TimerThread._nearest_run_time and fenced by TimerThread._mutex. // We can avoid touching the mutex and related cacheline when the @@ -204,7 +200,7 @@ TimerThread::Task* TimerThread::Bucket::consume_tasks() { BAIDU_SCOPED_LOCK(_mutex); if (_task_head) { head = _task_head; - _task_head = NULL; + _task_head = nullptr; _nearest_run_time = std::numeric_limits::max(); } } @@ -216,11 +212,11 @@ TimerThread::Bucket::schedule(void (*fn)(void*), void* arg, const timespec& abstime) { butil::ResourceId slot_id; Task* task = butil::get_resource(&slot_id); - if (task == NULL) { + if (task == nullptr) { ScheduleResult result = { INVALID_TASK_ID, false }; return result; } - task->next = NULL; + task->next = nullptr; task->fn = fn; task->arg = arg; task->run_time = butil::timespec_to_microseconds(abstime); @@ -285,7 +281,7 @@ TimerThread::TaskId TimerThread::schedule( int TimerThread::unschedule(TaskId task_id) { const butil::ResourceId slot_id = slot_of_task_id(task_id); Task* const task = butil::address_resource(slot_id); - if (task == NULL) { + if (task == nullptr) { LOG(ERROR) << "Invalid task_id=" << task_id; return -1; } @@ -492,14 +488,14 @@ void TimerThread::run() { expected_nsignals = _nsignals; } } - timespec* ptimeout = NULL; + timespec* ptimeout = nullptr; timespec next_timeout = { 0, 0 }; const int64_t now = butil::gettimeofday_us(); if (next_run_time != std::numeric_limits::max()) { int64_t wait_us = next_run_time - now; // Cap the sleep so we periodically wake up to drain buckets and // sweep the heap even when the nearest task is far in the future. - // Note: an empty heap keeps ptimeout NULL (sleep until woken by a + // Note: an empty heap keeps ptimeout nullptr (sleep until woken by a // schedule()), which is safe because the first task after the heap // empties is always earlier than _nearest_run_time and wakes us. const int64_t max_wakeup_us = @@ -532,19 +528,15 @@ void TimerThread::stop_and_join() { // stop_and_join was not called from a running task. // wake up the timer thread in case it is sleeping. futex_wake_private(&_nsignals, 1); - pthread_join(_thread, NULL); + pthread_join(_thread, nullptr); } } } static pthread_once_t g_timer_thread_once = PTHREAD_ONCE_INIT; -static TimerThread* g_timer_thread = NULL; +static TimerThread* g_timer_thread = nullptr; static void init_global_timer_thread() { - g_timer_thread = new (std::nothrow) TimerThread; - if (g_timer_thread == NULL) { - LOG(FATAL) << "Fail to new g_timer_thread"; - return; - } + g_timer_thread = new TimerThread; TimerThreadOptions options; options.bvar_prefix = "bthread_timer"; options.num_buckets = FLAGS_brpc_timer_num_buckets; @@ -552,7 +544,7 @@ static void init_global_timer_thread() { if (rc != 0) { LOG(FATAL) << "Fail to start timer_thread, " << berror(rc); delete g_timer_thread; - g_timer_thread = NULL; + g_timer_thread = nullptr; return; } } diff --git a/src/bthread/types.h b/src/bthread/types.h index d46de1e835..1fb7a5d0cb 100644 --- a/src/bthread/types.h +++ b/src/bthread/types.h @@ -110,7 +110,7 @@ typedef struct bthread_attr_t { void operator=(unsigned stacktype_and_flags) { stack_type = (stacktype_and_flags & 7); flags = (stacktype_and_flags & ~(unsigned)7u); - keytable_pool = NULL; + keytable_pool = nullptr; tag = BTHREAD_TAG_INVALID; } bthread_attr_t operator|(unsigned other_flags) const { @@ -131,22 +131,22 @@ void bthread_attr_set_name(bthread_attr_t* attr, const char* name); // obvious drawback is that you need more worker pthreads when you have a lot // of such bthreads. static const bthread_attr_t BTHREAD_ATTR_PTHREAD = -{ BTHREAD_STACKTYPE_PTHREAD, 0, NULL, BTHREAD_TAG_INVALID, {0} }; +{ BTHREAD_STACKTYPE_PTHREAD, 0, nullptr, BTHREAD_TAG_INVALID, {0} }; // bthreads created with following attributes will have different size of // stacks. Default is BTHREAD_ATTR_NORMAL. -static const bthread_attr_t BTHREAD_ATTR_SMALL = {BTHREAD_STACKTYPE_SMALL, 0, NULL, +static const bthread_attr_t BTHREAD_ATTR_SMALL = {BTHREAD_STACKTYPE_SMALL, 0, nullptr, BTHREAD_TAG_INVALID, {0}}; -static const bthread_attr_t BTHREAD_ATTR_NORMAL = {BTHREAD_STACKTYPE_NORMAL, 0, NULL, +static const bthread_attr_t BTHREAD_ATTR_NORMAL = {BTHREAD_STACKTYPE_NORMAL, 0, nullptr, BTHREAD_TAG_INVALID, {0}}; -static const bthread_attr_t BTHREAD_ATTR_LARGE = {BTHREAD_STACKTYPE_LARGE, 0, NULL, +static const bthread_attr_t BTHREAD_ATTR_LARGE = {BTHREAD_STACKTYPE_LARGE, 0, nullptr, BTHREAD_TAG_INVALID, {0}}; // bthreads created with this attribute will print log when it's started, // context-switched, finished. static const bthread_attr_t BTHREAD_ATTR_DEBUG = { - BTHREAD_STACKTYPE_NORMAL, BTHREAD_LOG_START_AND_FINISH | BTHREAD_LOG_CONTEXT_SWITCH, NULL, - BTHREAD_TAG_INVALID, {0}}; + BTHREAD_STACKTYPE_NORMAL, BTHREAD_LOG_START_AND_FINISH | BTHREAD_LOG_CONTEXT_SWITCH, + nullptr, BTHREAD_TAG_INVALID, {0}}; static const size_t BTHREAD_EPOLL_THREAD_NUM = 1; static const bthread_t BTHREAD_ATOMIC_INIT = 0; @@ -182,7 +182,7 @@ struct mutex_owner_t { typedef struct bthread_mutex_t { #if defined(__cplusplus) bthread_mutex_t() - : butex(NULL), csite{} + : butex(nullptr), csite{} , enable_csite(false) , owner{false, 0} {} @@ -203,7 +203,7 @@ typedef struct { typedef struct bthread_cond_t { #if defined(__cplusplus) - bthread_cond_t() : m(NULL), seq(NULL) {} + bthread_cond_t() : m(nullptr), seq(nullptr) {} DISALLOW_COPY_AND_ASSIGN(bthread_cond_t); #endif bthread_mutex_t* m; @@ -215,7 +215,7 @@ typedef struct { typedef struct bthread_sem_t { #if defined(__cplusplus) - bthread_sem_t() : butex(NULL), enable_csite(true) {} + bthread_sem_t() : butex(nullptr), enable_csite(true) {} DISALLOW_COPY_AND_ASSIGN(bthread_sem_t); #endif unsigned* butex; @@ -225,7 +225,7 @@ typedef struct bthread_sem_t { typedef struct bthread_rwlock_t { #if defined(__cplusplus) bthread_rwlock_t() - : writer_wait_count(0), lock_word(NULL) {} + : writer_wait_count(0), lock_word(nullptr) {} DISALLOW_COPY_AND_ASSIGN(bthread_rwlock_t); #endif // Number of writers currently in flight (used as a butex): diff --git a/src/bthread/unstable.h b/src/bthread/unstable.h index 186d9ce65b..f5c46ea2dd 100644 --- a/src/bthread/unstable.h +++ b/src/bthread/unstable.h @@ -63,7 +63,7 @@ extern int bthread_timer_del(bthread_timer_t id); extern int bthread_fd_wait(int fd, unsigned events); // Suspend caller thread until the file descriptor `fd' has `epoll_events' -// or CLOCK_REALTIME reached `abstime' if abstime is not NULL. +// or CLOCK_REALTIME reached `abstime' if abstime is not nullptr. // Returns 0 on success, -1 otherwise and errno is set. extern int bthread_fd_timedwait(int fd, unsigned epoll_events, const struct timespec* abstime); @@ -80,7 +80,7 @@ extern int bthread_close(int fd); extern int bthread_connect(int sockfd, const struct sockaddr* serv_addr, socklen_t addrlen); // Suspend caller thread until connect(2) on `sockfd' succeeds -// or CLOCK_REALTIME reached `abstime' if `abstime' is not NULL. +// or CLOCK_REALTIME reached `abstime' if `abstime' is not nullptr. extern int bthread_timed_connect(int sockfd, const struct sockaddr* serv_addr, socklen_t addrlen, const timespec* abstime); diff --git a/src/bthread/work_stealing_queue.h b/src/bthread/work_stealing_queue.h index 138aaa6ba8..37899abbcb 100644 --- a/src/bthread/work_stealing_queue.h +++ b/src/bthread/work_stealing_queue.h @@ -34,13 +34,13 @@ class WorkStealingQueue { WorkStealingQueue() : _bottom(1) , _capacity(0) - , _buffer(NULL) + , _buffer(nullptr) , _top(1) { } ~WorkStealingQueue() { delete [] _buffer; - _buffer = NULL; + _buffer = nullptr; } int init(size_t capacity) { @@ -57,10 +57,7 @@ class WorkStealingQueue { << " which must be power of 2"; return -1; } - _buffer = new(std::nothrow) T[capacity]; - if (NULL == _buffer) { - return -1; - } + _buffer = new T[capacity]; _capacity = capacity; return 0; }