2011-11-03 51 views
2

直到std::atomic可用,什麼是多平臺(windows & linux)的方式自動遞增變量?多平臺原子增量

我目前使用boost::detail::atomic_count,但它在boost::detail命名空間,我不知道它是否安全使用。

+1

你有沒有看當前在審查[Boost.Atomic](http://www.chaoticmind.net/~ hcb/projects/boost.atomic/doc/index.html)庫? – ildjarn

+1

'std :: atomic'已經可用。沒有? – 2011-11-03 19:32:51

+0

MSVC和GCC現在都有std :: atomic支持。還有http://www.stdthread.co.uk – Eloff

回答

2

A 多平臺,但編譯器的具體方式是使用GCC的__sync_fetch_and_add

或定義這樣一個自己的功能有位條件編譯:

#ifdef __GNUC__ 
#define atomic_inc(ptr) __sync_fetch_and_add ((ptr), 1) 
#elif defined (_WIN32) 
#define atomic_inc(ptr) InterlockedIncrement ((ptr)) 
#else 
#error "Need some more porting work here" 
#endif 
+4

__sync_fetch_and_add和MSVC InterlockedIncrement在返回類型中不等效。 __sync_fetch_and_add返回ptr的* previous *值,InterlockedIncrement返回增加的ptr的結果值。你需要使用的是「__sync_add_and_fetch」是等同/可互換的。 –

+0

此外,'InterlockedIncrement'僅適用於32位值。 – rubenvb