AFAIK सी ++ एटोमिक्स (<atomic>
) परिवार 3 लाभ प्रदान करते हैं:सी ++ एटोमिक्स और पार धागा दृश्यता
- आदिम निर्देश अविभाज्यता (कोई गंदा पढ़ता है),
- स्मृति आदेश (दोनों, सीपीयू और संकलक के लिए) और
- क्रॉस-थ्रेड दृश्यता/परिवर्तन प्रसार।
और मुझे तीसरी गोली के बारे में निश्चित नहीं है, इस प्रकार निम्नलिखित उदाहरण देखें।
#include <atomic>
std::atomic_bool a_flag = ATOMIC_VAR_INIT(false);
struct Data {
int x;
long long y;
char const* z;
} data;
void thread0()
{
// due to "release" the data will be written to memory
// exactly in the following order: x -> y -> z
data.x = 1;
data.y = 100;
data.z = "foo";
// there can be an arbitrary delay between the write
// to any of the members and it's visibility in other
// threads (which don't synchronize explicitly)
// atomic_bool guarantees that the write to the "a_flag"
// will be clean, thus no other thread will ever read some
// strange mixture of 4bit + 4bits
a_flag.store(true, std::memory_order_release);
}
void thread1()
{
while (a_flag.load(std::memory_order_acquire) == false) {};
// "acquire" on a "released" atomic guarantees that all the writes from
// thread0 (thus data members modification) will be visible here
}
void thread2()
{
while (data.y != 100) {};
// not "acquiring" the "a_flag" doesn't guarantee that will see all the
// memory writes, but when I see the z == 100 I know I can assume that
// prior writes have been done due to "release ordering" => assert(x == 1)
}
int main()
{
thread0(); // concurrently
thread1(); // concurrently
thread2(); // concurrently
// join
return 0;
}
सबसे पहले, कृपया कोड में मेरी धारणाओं को मान्य करें (विशेष रूप से thread2
)।
दूसरा, मेरे सवालों हैं:
a_flag
कैसे लिख सकता हूँ करता अन्य कोर तक पहुंचने में?std::atomic
अन्य कोर कैश के साथ लेखक कैश मेंa_flag
सिंक्रनाइज़ करता है (MESI का उपयोग कर, या कुछ और), या प्रचार स्वचालित है?मानते हैं कि किसी विशेष मशीन पर ध्वज को लिखना परमाणु (x86 पर int_32 लगता है) और हमारे पास सिंक्रनाइज़ करने के लिए कोई निजी स्मृति नहीं है (हमारे पास केवल ध्वज है) क्या हमें परमाणुओं का उपयोग करने की आवश्यकता है?
को ध्यान में लेते हुए सबसे लोकप्रिय सीपीयू आर्किटेक्चर (x86, x64, एआरएम v.whatever, IA-64), क्रॉस-कोर दृश्यता (मैं अब नहीं पर विचार reorderings हूँ) स्वत: (परन्तु संभवत: देरी) है, या आपको डेटा के किसी भी हिस्से को प्रसारित करने के लिए विशिष्ट आदेश जारी करने की आवश्यकता है?