该程序有时会打印 00,但如果我注释掉 a.store 和 b.store 并取消注释 a.fetch_add 和 b.fetch_add ,它们执行完全相同的操作,即都设置 a=1,b=1 的值,我从不得到00。(在 x86-64 Intel i3 上测试,使用 g++ -O2)
我是不是遗漏了什么,或者按照标准“00”永远不会出现?
这是带有普通商店的版本,可以打印00。
// g++ -O2 -pthread axbx.cpp ; while [ true ]; do ./a.out | grep "00" ; done
#include<cstdio>
#include<thread>
#include<atomic>
using namespace std;
atomic<int> a,b;
int reta,retb;
void foo(){
//a.fetch_add(1,memory_order_relaxed);
a.store(1,memory_order_relaxed);
retb=b.load(memory_order_relaxed);
}
void bar(){
//b.fetch_add(1,memory_order_relaxed);
b.store(1,memory_order_relaxed);
reta=a.load(memory_order_relaxed);
}
int main(){
thread t[2]{ thread(foo),thread(bar) };
t[0].join(); t[1].join();
printf("%d%d\n",reta,retb);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
下面从不打印 00
// g++ -O2 -pthread axbx.cpp …Run Code Online (Sandbox Code Playgroud) c++ multithreading cpu-architecture memory-barriers stdatomic
template<typename T>
void func(const T &x) {
cout << "base template "<<x<<"\n";
}
template<>
void func(const int &x) {
cout << "int specialization "<<x<<"\n";
}
template<>
void func(const double &x) {
cout << "double specialization "<<x<<"\n";
}
int main() {
int five = 5;
func(five); // prints int specialization 5
double d = 3.14;
func<int>(d); // prints int specialization 3
}
Run Code Online (Sandbox Code Playgroud)
现在已const删除
template<typename T>
void func( T &x) {
cout << "base template "<<x<<"\n";
}
template<>
void func( …Run Code Online (Sandbox Code Playgroud) template<typename T>
void func(T t) {
cout << "func(T t)" << endl;
}
struct X {};
template<> // template specialization of func
void func(const X& x) {
cout << "func( X& x)" << endl;
}
X x ;
const X& y = x;
func(x);
func(y);
Run Code Online (Sandbox Code Playgroud)
始终调用 func(T t)。我不想显式调用 func<const X&>(y) 在这种情况下它会调用第二个函数。