包含指针的原子结构 [英] Atomic struct containing pointer

查看:82
本文介绍了包含指针的原子结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <atomic>
#include <iostream>

using namespace std;

struct Simple{
    int a = 0;
    int b = 0;
};

struct WithPointer{
    int *a = nullptr;
    int b = 0;
};

int main(int argc, char const *argv[])
{
    atomic<Simple> simple;
    cout<<simple.is_lock_free()<<"\n";
    
    atomic<Simple*> simple_p;
    cout<<simple_p.is_lock_free()<<"\n";

    atomic<WithPointer> with_pointer;
    cout<<with_pointer.is_lock_free()<<"\n";

    return 0;
}

此示例对于Simple结构很好,但对于WithPointer结构却不能正常工作. 我收到以下编译错误,为什么? 我该怎么办.

This example works fine for the Simple struct but not for the WithPointer struct. I get the following compile error, why? What can I do.

g++ main.cpp
/usr/bin/ld: /tmp/cc49YEoR.o: in function `std::atomic<WithPointer>::is_lock_free() const':
1a.cpp:(.text._ZNKSt6atomicI11WithPointerE12is_lock_freeEv[_ZNKSt6atomicI11WithPointerE12is_lock_freeEv]+0x1d): undefined reference to `__atomic_is_lock_free'
collect2: error: ld returned 1 exit status

推荐答案

您需要使用clang和gcc上的-latomic标志编译程序. 演示.

You need to compile the program with the -latomic flag on clang and gcc. demo.

这篇关于包含指针的原子结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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