what are the difference in memory_order_seq_cst with other memory order?
Is there a table to summarize the difference in memory order? such as which situation to use each memory order
moreover, what is the difference between memory order and (data_cond and future)?
is it
1. memory order is for waiting
2. 开发者_StackOverflow社区data_cond is for waiting
3. future is for doing other thing while waiting
Memory orders are used to specify memory ordering in atomic operations. The simplest memory order is memory_order_seq_cst
which gives you sequential consistency. Other memory models give relaxed momory orderings.
If you want to get an acquire-release ordering you are expected to combine: memory_order_consume
, memory_order_acquire
, memory_order_release
, and
memory_order_acq_rel
.
If you want to get a relaxed ordering you are expected to use memory_order_relaxed
.
Here is a simple example of using memory ordering to implement a spin-lock mutex:
class spinlock_mutex {
private:
std::atomic_flag f;
public:
spinlock_mutex() : f(ATOMIC_FLAG_INIT) {}
void lock() {
while (f.test_and_set(std::memory_order_acquire)) {}
}
void unlock() {
flag.clear(std::memory_order_release());
}
};
There is data_cond type in C++11. I figure out you may be referring to std::condition_variable
which is a condition variable to be associated to a mutex.
std::mutex m;
std::queue<request> q;
std::condition_variable cv;
void producer() {
while (more_data()) {
request r = generate_request();
std::lock_guard<std::mutex> l(m);
q.push(r);
cv.notify_one();
}
}
void consumer() {
for (;;) {
std::unique_lock<std::mutex> l(m);
cv.wait(l, []{ return !q.empty();});
request r = q.front();
l.unlock();
process_request(r);
if (is_last(r)) break;
}
}
Finally, a future allows that a thread may return a value to the code section which made the invocation.
int main() {
std::future<int> r = std::async(do_something, 1, 10);
do_something_else();
std::cout << “Result= “ << r.get() << std::endl;
return 0;
}
精彩评论