gpt4 book ai didi

c++ - 我的 std::lock 实现中的总线错误

转载 作者:行者123 更新时间:2023-11-30 03:16:43 25 4
gpt4 key购买 nike

我正在尝试实现 std::lock .策略是try_lock()每个互斥锁,如果我失败了,我解锁所有锁定的互斥锁并从下一个互斥锁开始。当我运行这段代码时,我收到了 Bus Error: 10(尽管并非总是如此)。我无法理解我哪里出错了。

用 gcc 和 clang 编译 - 结果相同。

代码:

#include <iostream>
#include <string>
#include <mutex>
#include <thread>

using namespace std;
int counter = 0;
std::mutex m1,m2,m3;

//base case
template <typename T>
void unlock_all(T& obj)
{
obj.unlock();
}

// just keep unlocking!
template<typename T, typename... Args>
void unlock_all(T& obj, Args&... rest)
{
obj.unlock();
unlock_all(rest...);
}


template <typename T>
void unlock_last(T& obj)
{
obj.unlock();
}

template <typename T, typename... Args>
void unlock_last(T& obj, Args&... rest)
{
if(counter == sizeof...(rest))
{
unlock_all(rest...);
return;
}
else
{
unlock_last(rest...);
}

}

template <typename T, typename... Args>
void lock_all(T& obj, Args&... rest)
{

if(counter == (1 + sizeof...(rest)))
{
cout << "all locked!" << endl;
//unlock all now
unlock_all(rest...,obj);
return;
}

if(obj.try_lock())
{
counter++;
lock_all(rest...,obj);
}
else
{
// Here, if counter is NOT 0, we should unlock all the locks we have locked earlier and
// try to lock from the next lock in line. We can use counter to find the
// locks that are locked.
if(counter == 0)
{
lock_all(rest...,obj);
}
else
{
unlock_last(rest...);
counter = 0;
lock_all(rest...,obj);
}
}
}

void func1()
{
m1.lock();
cout << "THREAD 1 printing " << endl;
m1.unlock();
}
void func2()
{
m2.lock();
cout << "THREAD 2 printing " << endl;
m2.unlock();
}
void func3()
{
m3.lock();
cout << "THREAD 3 printing " << endl;
m3.unlock();
}

void func()
{
lock_all(m1,m2,m3);
}
int main()
{

std::thread t1(func1);
std::thread t2(func2);
std::thread t3(func3);
std::thread t4(func);

t1.join();
t2.join();
t3.join();
t4.join();

}

不太确定如何调试它。代码非常简单;我可以在这里做什么?在这上面花了几天时间,但没有取得任何进展。

最佳答案

unlock_last 的可变参数版本总是假设第一个参数没有被锁定。因此,在

        unlock_last(rest...);
counter = 0;
lock_all(rest...,obj);

如果 counter == sizeof...(rest) 在你输入这个之前(即,你已经锁定了除 lock_all 的第一个参数之外的所有内容),那么调用 unlock_last 实际上不会解锁您锁定的所有内容。

(我希望这只是一个概念证明,因为同步函数中的可变全局状态只是......不。)

关于c++ - 我的 std::lock 实现中的总线错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56070648/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com