C++11 递归自旋锁实现

C++11 Recursive Spinlock Implementation

本文关键字:实现 递归 C++11      更新时间:2023-10-16

在这篇代码审查文章之后,我尝试实现递归旋转锁,如下所示。

class SpinLock {
public:
SpinLock() : lock_owner(lock_is_free), lock_count(0) {
}
inline bool tryLock() {
if (lock_owner != std::this_thread::get_id()) {
bool locked = lock_owner.compare_exchange_strong(lock_is_free,
std::this_thread::get_id(), std::memory_order_acquire,
std::memory_order_relaxed);
if (locked) {
lock_count++;
}
return locked;
}
lock_count++;
return true;
}
inline void lock() {
if (lock_owner != std::this_thread::get_id()) {
while(!lock_owner.compare_exchange_weak(lock_is_free,
std::this_thread::get_id(), std::memory_order_acquire,
std::memory_order_relaxed));
assert(lock_owner == std::this_thread::get_id());
} else {
printf("Recursive lockingn");
}
lock_count++;
}
inline void unlock() {
assert(lock_owner == std::this_thread::get_id());
assert(lock_count != 0);
--lock_count;
if (lock_count == 0) {
lock_owner.store(lock_is_free, std::memory_order_release);
}
}
inline bool isOwner() {
return lock_owner == std::this_thread::get_id();
}
inline bool isSet() {
return lock_owner != lock_is_free;
}

private:
std::thread::id lock_is_free;
std::atomic<std::thread::id> lock_owner;
int lock_count;
};

但是当我尝试使用多个线程锁定时,锁定方法似乎并不能确保相互排斥。我在这里做错了什么?

正如注释中指出的,如果条件为 false,compare_exchange_weak替换第一个参数的内容,因此lock_is_free已损坏。

此外,这不是有效的代码,因为compare_exchange_weak按位顺序比较存储在atomic变量中的对象的值,因此就好像它们是使用std::memcmp进行比较一样。 并且类型std::thread::id的对象不是整型类型,并且具有用于比较的特殊重载。pthread_t也是如此(pthread_equal),所以本质上你依赖于实现定义的行为。

您可以通过运行以下代码来确认这一点

#include <type_traits>
#include <iostream>
#include <thread>
#include <pthread.h>
using std::cout;
using std::endl;
int main() {
cout << std::boolalpha << std::is_integral<std::thread::id>::value << endl;
cout << std::boolalpha << std::is_integral<decltype(pthread_self())>::value
<< endl;
return 0;
}

在这种情况下,为什么不直接重载memcpymemcmpstd::thread::id一起工作呢? cpp首选项和 cplusplus.com 都确认没有保证。 甚至重载memcpy(全局和std命名空间)在我的系统上使用我的标准库也不起作用。 我怀疑它不会在大多数其他系统(标准库和编译器组合)上也是如此,原因有两个:

  1. compare_exchange_weak可能不会在引擎盖下使用memcpymemcmp,并且可能会自行实现
  2. 尽管在将指针传递给memcpy之前不需要将指针转换为void*,但无论如何memcmp可能会选择默认实现
  3. ,但这是不正确的

请参阅下面的代码,了解我在第二点中的意思

void func(void*) {
cout << "void*" << endl;
}
void func(int*) {
cout << "int*" << endl;
}
int main() {
int a = 1;
func(&a);
func(reinterpret_cast<void*>(a));
return 0;
}

要回答您的问题,将compare_exchange_weakstd::thread::id一起使用是不正确的("不可移植"可能更好)代码。