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

// Authors: Ge,Jun (gejun@baidu.com)
//          Jiashun Zhu(zhujiashun@baidu.com)

gejun's avatar
gejun committed
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
#ifndef BUTIL_COMPAT_H
#define BUTIL_COMPAT_H

#include "butil/build_config.h"
#include <pthread.h>

#if defined(OS_MACOSX)

#include <sys/cdefs.h>
#include <stdint.h>
#include <dispatch/dispatch.h>    // dispatch_semaphore
#include <errno.h>                // EINVAL

__BEGIN_DECLS

// Implement pthread_spinlock_t for MAC.
34 35 36
struct pthread_spinlock_t {
    dispatch_semaphore_t sem;
};
37
inline int pthread_spin_init(pthread_spinlock_t *__lock, int __pshared) {
38 39 40 41
    if (__pshared != 0) {
        return EINVAL;
    }
    __lock->sem = dispatch_semaphore_create(1);
gejun's avatar
gejun committed
42 43
    return 0;
}
44
inline int pthread_spin_destroy(pthread_spinlock_t *__lock) {
45
    // TODO(gejun): Not see any destructive API on dispatch_semaphore
gejun's avatar
gejun committed
46 47 48
    (void)__lock;
    return 0;
}
49
inline int pthread_spin_lock(pthread_spinlock_t *__lock) {
50
    return (int)dispatch_semaphore_wait(__lock->sem, DISPATCH_TIME_FOREVER);
gejun's avatar
gejun committed
51
}
52
inline int pthread_spin_trylock(pthread_spinlock_t *__lock) {
53
    if (dispatch_semaphore_wait(__lock->sem, DISPATCH_TIME_NOW) == 0) {
54 55 56
        return 0;
    }
    return EBUSY;
gejun's avatar
gejun committed
57
}
58
inline int pthread_spin_unlock(pthread_spinlock_t *__lock) {
59
    return dispatch_semaphore_signal(__lock->sem);
gejun's avatar
gejun committed
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
}

__END_DECLS

#elif defined(OS_LINUX)

#include <sys/epoll.h>

#else

#error "The platform does not support epoll-like APIs"

#endif // defined(OS_MACOSX)

__BEGIN_DECLS

inline uint64_t pthread_numeric_id() {
#if defined(OS_MACOSX)
    uint64_t id;
    if (pthread_threadid_np(pthread_self(), &id) == 0) {
        return id;
    }
    return -1;
#else
    return pthread_self();
#endif
}

__END_DECLS

#endif // BUTIL_COMPAT_H