链接pthread禁用无锁shared_ptr实现 [英] Linking pthread disables lock-free shared_ptr implementation

查看:226
本文介绍了链接pthread禁用无锁shared_ptr实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标题几乎传达所有相关信息,但这里是一个最小的重现:

The title pretty much conveys all relevant information, but here's a minimal repro:

#include <atomic>
#include <cstdio>
#include <memory>

int main() {
    auto ptr = std::make_shared<int>(0);
    bool is_lockless = std::atomic_is_lock_free(&ptr);
    printf("shared_ptr is lockless: %d\n", is_lockless);
}

使用以下编译器选项进行编译会产生无锁的 shared_ptr 实现:

Compiling this with the following compiler options produces a lock-free shared_ptr implementation:

g++ -std=c++11 -march=native main.cpp

虽然这不:

g++ -std=c++11 -march=native -pthread main.cpp


b $ b

GCC 版本: 5.3.0 (在Linux上,使用 libstdc ++ ),在多台计算机上进行测试,这些计算机应该具有必要的原子指令,以使此工作。

GCC version: 5.3.0 (on Linux, using libstdc++), tested on multiple machines that should have the necessary atomic instructions to make this work.

有任何方式强制无锁实现(我需要锁定版本,不管性能)?

Is there any way to force the lock-free implementation (I'd need the lock-free version, regardless of performance)?

推荐答案

如果在线程环境中使用 shared_ptr 有一些锁[他们可以实现为原子增量和减量,但可能有一些地方需要一个更大的锁来确保没有竞争]。无锁版本只有在只有一个线程时才有效。如果你不使用线程,不要链接 -lpthread

If you use shared_ptr in a threaded environment, you NEED to have locks [of some kind - they could be implemented as atomic increment and decrement, but there may be places where a "bigger" lock is required to ensure no races]. The lockless version only works when there is only one thread. If you are not using threads, don't link with -lpthread.

我确定有一些棘手的方法来说服编译器,你不是真正地使用线程的共享指针,但你真的在脆弱的领域,如果你do - 如果 shared_ptr 传递给线程会发生什么?你可能可以保证现在,但有人可能会意外或有目的地把一个在不同的线程中运行的东西,并且一切都会中断。

I'm sure there is some tricky way to convince the compiler that you are not REALLY using the threads for your shared pointers, but you are REALLY in fragile territory if you do - what happens if a shared_ptr is passed to a thread? You may be able to guarantee that NOW, but someone will probably accidentally or on purpose introduce one into something that runs in a different thread, and it all breaks.

这篇关于链接pthread禁用无锁shared_ptr实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆