Skip to content

Instantly share code, notes, and snippets.

@imsjz
Created February 17, 2020 09:41
Show Gist options
  • Save imsjz/356099a45624631de67cffc2c13b356d to your computer and use it in GitHub Desktop.
Save imsjz/356099a45624631de67cffc2c13b356d to your computer and use it in GitHub Desktop.
有关volatile的例子。一般用atomic来保存多线程的同步性,而非volatile。
#include <iostream>
#include <thread>
// 这个链接说这样写会产生问题,但是在mac上测试并没有问题
// 链接:https://liam.page/2018/01/18/volatile-in-C-and-Cpp/
namespace sanjay1 {
bool flag = false;
using Type = int;
void test_volatile_demo() {
flag = false;
Type* value = new Type(1);
auto func_thread2 = [](Type* value)->void {
// do something
std::cout << "func_thread2 begin" << std::endl;
*value = 22;
flag = true;
};
std::thread t(func_thread2, value);
while (true) {
if(flag == true) {
std::cout << "applay value: " << *value << std::endl;
break;
}
}
t.join();
if(value != nullptr) {
delete value;
}
}
}
// 更好的写法
#include <atomic>
namespace sanjay2{
std::atomic<bool> flag = false;
using Type = int;
void test_volatile_demo() {
flag = false;
Type* value = new Type(1);
auto func_thread2 = [](Type* value)->void {
// do something
std::cout << "func_thread2 begin" << std::endl;
*value = 22;
flag = true;
};
std::thread t(func_thread2, value);
while (true) {
if(flag == true) {
std::cout << "applay value: " << *value << std::endl;
break;
}
}
t.join();
if(value != nullptr) {
delete value;
}
}
}
int main() {
for(size_t i = 0; i < 1000000000; ++i) {
sanjay2::test_volatile_demo();
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment