假设countMe是一个全局变量,并且我同时向这个 while 循环启动 10 个线程,变量countMe互斥体是否在谓词中受保护?我认为因为当代码到达 wait_for 时它会解锁并释放锁,因此变量 countMe 不受互斥保护。我对吗?
while (true)
{
std::unique_lock<std::mutex> lock(mtx_kill);
cv_kill.wait_for(lock, 500ms, [&]() {++countMe; return killFlag; });
if (killFlag)
{
break;
}
}
Run Code Online (Sandbox Code Playgroud) std::shared_ptr<Dog> pd;
void F() {
pd = std::make_shared<Dog>("Smokey");
}
int main() {
std::thread t1(F);
std::thread t2(F);
t1.join();
t2.join();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
std::shared_ptr<Dog> pd(new Dog("Gunner"));
void F() {
std::shared_ptr<Dog> localCopy = pd;
}
int main() {
std::thread t1(F);
std::thread t2(F);
t1.join();
t2.join();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在 C++ 中,我知道 std::shared_ptr 对于读取和复制来说是线程安全的。但我对何时需要使用互斥体来同步线程有点困惑。我有两个代码片段。在第一个中,std::shared_ptr 被多个线程修改。在第二个线程中,每个线程仅读取和复制共享指针。在这两种情况下我都需要互斥体,还是只在第一种情况下需要互斥体?为什么或者为什么不?”
我已经在 StackOverflow 中看到了有关此类似错误的所有帖子,但仍然找不到导致我的问题的原因。
我用来std::dynamic_pointer_cast将std::shared_ptr<Base>对象转换为std::shared_ptr<DerivedShared>对象,但遇到“尝试引用已删除的函数”错误。我已确保Base析构函数是虚拟的,但错误仍然存在。
可能是什么原因导致此错误?我该如何解决它?标准库中是否存在任何可能导致此问题的已知限制或错误?任何见解或建议将不胜感激。
PS:我知道它可以工作,static_pointer_cast但想知道是什么导致了问题dynamic_pointer_cast!
struct Base
{
Base() = default;
virtual ~Base() = default;
//Copy
Base(const Base&) = default;
Base& operator=(const Base&) = default;
//Move
Base(Base&&) = default;
Base& operator=(Base&&) = default;
};
struct DerivedShared : public Base
{
public:
DerivedShared() //: data(std::shared_ptr<int[]>(new int[3]{1,2,3}))
{
//data = std::make_shared<int[]>(new int[3]{ 1,2,3 });
data = std::shared_ptr<int[]>(new int[3]{ 1,2,3 });
}
public:
std::shared_ptr<int[]> data;
};
int main()
{ …Run Code Online (Sandbox Code Playgroud) 我正在使用一段涉及银行帐户转账的多线程代码。目标是在账户之间安全地转账,而不会遇到竞争条件。我用来std::mutex在转账过程中保护银行账户余额:
std::unique_lock我的问题集中在with的使用上std::lock。我没有将std::mutex对象直接传递给std::lock,而是将它们包装起来std::unique_lock并将它们传递给std::lock。
如何std::lock与对象一起工作std::unique_lock?
负责std::lock实际锁定from和to互斥锁,而std::unique_lock对象仅管理锁(即,当它们超出范围时释放它们)?
是否std::lock调用lock()的方法std::unique_lock?
std::unique_lock与std::lock直接将std::mutex对象传递给相比,使用 with 有何优点std::lock?
struct bank_account
{
bank_account(int balance) :
mtx(), balance{ balance }
{}
std::mutex mtx;
int balance;
};
void transfer(bank_account& from, bank_account& to, int amount)
{
std::unique_lock<std::mutex> from_Lock(from.mtx, std::defer_lock);
std::unique_lock<std::mutex> to_Lock(to.mtx, std::defer_lock);
std::lock(from_Lock, to_Lock);
if (amount …Run Code Online (Sandbox Code Playgroud)