1. 程式人生 > >3.原子變量

3.原子變量

iostream 原子變量 () mes 結果 多線程操作 include AD windows

全局變量,多線程操作不安全,可能會導致結果不安全

互斥鎖,操作很慢,但是結果正確

原子變量,操作很快,結果正確

代碼示例

 1 #include <Windows.h>
 2 #include <thread>
 3 #include <iostream>
 4 #include <tuple>
 5 using namespace std;
 6 
 7 void run()
 8 {
 9     MessageBox(0, L"hello", L"hello", 0);
10 }
11 
12 void runA(const wchar_t *s, const
wchar_t *b) 13 { 14 MessageBox(0, s, b, 0); 15 } 16 17 class myclass 18 { 19 public: 20 void operator()()//C++重載 21 { 22 MessageBox(0, L"hello", L"hello", 0); 23 } 24 }; 25 26 void main1() 27 { 28 thread t1[3]{ thread(run),thread(run),thread(run) }; 29 30 thread *p1 = new
thread(run); 31 thread *p2 = new thread(run); 32 33 thread *p(new thread[3]{ thread(run),thread(run),thread(run) }); 34 //偽函數 35 thread t3[3]{ thread(myclass()),thread(myclass()) ,thread(myclass()) }; 36 system("pause"); 37 } 38 39 void main() 40 { 41 //多線程帶參數 42 thread t1(runA, L"
木頭人1", L"HELLO"); 43 thread t2(runA, L"木頭人1", L"HELLO"); 44 thread t3(runA, L"木頭人1", L"HELLO"); 45 46 //tuple數組 47 char ch = X; 48 short sh = 129; 49 int num = 1234; 50 char *p = "木頭人"; 51 tuple<char, short, int, char *>mytuple(ch, sh, num, p); 52 auto i0 = get<0>(mytuple); 53 cout << i0 << endl; 54 auto i1 = get<1>(mytuple); 55 cout << i1 << endl; 56 auto i2 = get<2>(mytuple); 57 cout << i2 << endl; 58 auto i3 = get<3>(mytuple); 59 cout << i3 << endl; 60 cin.get(); 61 }

3.原子變量