compat.h 2.43 KB
Newer Older
1 2 3 4 5 6 7
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you 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
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11 12 13 14 15 16
// 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.
17 18 19 20

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

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

__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