6

我没有在 Mac 中找到它,但几乎所有的 Linux 操作系统都支持它.. 有人知道如何将它移植到 mac 上吗?

4

4 回答 4

10

这是替换代码。您应该能够将其放在头文件中并将其放入您的项目中。

typedef int pthread_spinlock_t;

int pthread_spin_init(pthread_spinlock_t *lock, int pshared) {
    __asm__ __volatile__ ("" ::: "memory");
    *lock = 0;
    return 0;
}

int pthread_spin_destroy(pthread_spinlock_t *lock) {
    return 0;
}

int pthread_spin_lock(pthread_spinlock_t *lock) {
    while (1) {
        int i;
        for (i=0; i < 10000; i++) {
            if (__sync_bool_compare_and_swap(lock, 0, 1)) {
                return 0;
            }
        }
        sched_yield();
    }
}

int pthread_spin_trylock(pthread_spinlock_t *lock) {
    if (__sync_bool_compare_and_swap(lock, 0, 1)) {
        return 0;
    }
    return EBUSY;
}

int pthread_spin_unlock(pthread_spinlock_t *lock) {
    __asm__ __volatile__ ("" ::: "memory");
    *lock = 0;
    return 0;
}

请参阅讨论Github 源

编辑:这是一个适用于所有操作系统的类,其中包括在 OSX 上缺少 pthread 自旋锁的解决方法:

class Spinlock
{
private:    //private copy-ctor and assignment operator ensure the lock never gets copied, which might cause issues.
    Spinlock operator=(const Spinlock & asdf);
    Spinlock(const Spinlock & asdf);
#ifdef __APPLE__
    OSSpinLock m_lock;
public:
    Spinlock()
    : m_lock(0)
    {}
    void lock() {
        OSSpinLockLock(&m_lock);
    }
    bool try_lock() {
        return OSSpinLockTry(&m_lock);
    }
    void unlock() {
        OSSpinLockUnlock(&m_lock);
    }
#else
    pthread_spinlock_t m_lock;
public:
    Spinlock() {
        pthread_spin_init(&m_lock, 0);
    }

    void lock() {
        pthread_spin_lock(&m_lock);
    }
    bool try_lock() {
        int ret = pthread_spin_trylock(&m_lock);
        return ret != 16;   //EBUSY == 16, lock is already taken
    }
    void unlock() {
        pthread_spin_unlock(&m_lock);
    }
    ~Spinlock() {
        pthread_spin_destroy(&m_lock);
    }
#endif
};
于 2012-10-31T04:29:47.790 回答
7

尝试改用 OSSpinLock。文档在这里:http: //developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/spinlock.3.html

于 2011-11-18T02:40:43.897 回答
2

如果您的锁的性能不重要,pthread_mutex_t 可以用作 pthread_spinlock_t 的替代品,这使得移植变得容易。

于 2012-10-11T12:38:59.817 回答
0

我改用了(OS X intel 原生支持)

  1. pthread_rwlock_t 锁;
  2. pthread_rwlock_init
  3. pthread_rwlock_wrlock
  4. pthread_rwlock_unlock

这也很好用

于 2021-01-05T15:25:46.880 回答