【C/C++】标准库之 atomic

Backto C/C++ Index


atomic 指的是原子操作, 一个一个来, 谁也别抢, 急也没用. 只要用于对内存数据的原子保护.

Atomic types are types that encapsulate a value whose access is guaranteed to not cause data races and can be used to synchronize memory accesses among different threads.

This header declares two C++ classes, atomic and atomic_flag, that implement all the features of atomic types in self-contained classes. The header also declares an entire set of C-style types and functions compatible with the atomic support in C.

// atomic::operator=/operator T example:
#include        // std::cout
#include          // std::atomic
#include          // std::thread, std::this_thread::yield

std::atomic<int> foo = 0;

void set_foo(int x) {
	foo = x;
}

void print_foo() {
	while (foo == 0) {             // wait while foo=0
		std::this_thread::yield();
	}
	std::cout << "foo: " << foo << '\n';
}

int main()
{
	std::thread first(print_foo);
	std::thread second(set_foo, 10);
	first.join();
	second.join();
	return 0;
}
---
=> 10

std::atomic 是一个 template class, 上面的例子中首先声明了一个 atomic_int 类型的变量 foo. 然后两个线程一个去读取, 一个去修改.

Ref

  • http://www.cplusplus.com/reference/atomic/

你可能感兴趣的:(C/C++)