Is it possible to get the address of the underlyin

2019-07-18 08:59发布

I want to use an std::atomic_int with the futex linux function.

However, the futex function requires an address location, and I am uncertain about the correctness of just using the address of the atomic_int object.

Therefore, I wonder if it is possible to get the address of the underlying storage for an atomic_int, so I can then pass it to the futex call.

2条回答
趁早两清
2楼-- · 2019-07-18 09:38

Maybe not.

In manual

int futex(int *uaddr, int op, int val, const struct timespec *timeout,
    int *uaddr2, int val3);

The uaddr argument needs to point to an aligned integer which stores the counter.  The operation to execute  is  passed via the op argument, along with a value val.

Your atomic_int should be aligned.

In gcc 4.7.2 (which on Fedora 18), file: /usr/include/c++/4.7.2/bits/atomic_base.h

// Base types for atomics.
template<typename _IntTp>
  struct __atomic_base;
...
/// atomic_int
typedef __atomic_base<int>                    atomic_int;
...
template<typename _ITp>
struct __atomic_base
{
private:
  typedef _ITp      __int_type;

  __int_type        _M_i;

// some operations
...

atomic_int is just a wrapper of data __int_type _M_i; where __int_type is the template parameter you pass in. So it's an integer. And the struct is not guaranteed aligned in cross platform.

查看更多
冷血范
3楼-- · 2019-07-18 09:46

Portably, no. Realistically, an atomic_int is probably just sizeof(int) bytes of memory like a regular int on any modern C++ implementation. If sizeof(std::atomic<int>) == sizeof(int), go for broke and just pass its address to futex and see what happens.

查看更多
登录 后发表回答