我在Mac上找不到它,但几乎所有Linux操作系统都支持它。 任何人都知道如何将它移植到mac?
答案 0 :(得分:9)
这是替换代码。您应该能够将其放在头文件中并将其放入项目中。
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;
}
编辑:这是一个适用于所有操作系统的类,其中包含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
};
答案 1 :(得分:7)
尝试使用OSSpinLock。文档在这里:http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/spinlock.3.html
答案 2 :(得分:2)
如果锁的性能不重要,pthread_mutex_t可以用作pthread_spinlock_t的drop替换,这使得移植变得容易。
答案 3 :(得分:0)
我改用了(OS X intel 原生支持)
而且效果也很好