File tree Expand file tree Collapse file tree 1 file changed +53
-1
lines changed Expand file tree Collapse file tree 1 file changed +53
-1
lines changed Original file line number Diff line number Diff line change 1
- 1
1
+ #include < thread>
2
+ #include < atomic>
3
+ #include < iostream>
4
+ #include < list>
5
+
6
+ using namespace std ;
7
+
8
+ atomic_int iCount (0 );
9
+
10
+ void threadfun1 ()
11
+ {
12
+ for (int i =0 ; i< 1000 ; i++)
13
+ {
14
+ printf (" iCount:%d\r\n " , iCount++);
15
+ }
16
+ }
17
+ void threadfun2 ()
18
+ {
19
+ for (int i =0 ; i< 1000 ; i++)
20
+ {
21
+ printf (" iCount:%d\r\n " , iCount--);
22
+ }
23
+ }
24
+
25
+ int main ()
26
+ {
27
+ std::list<thread> lstThread;
28
+ for (int i=0 ; i< 100 ; i++)
29
+ {
30
+ lstThread.push_back (thread (threadfun1));
31
+ }
32
+ for (int i=0 ; i< 100 ; i++)
33
+ {
34
+ lstThread.push_back (thread (threadfun2));
35
+ }
36
+
37
+ for (auto & th: lstThread)
38
+ {
39
+ th.join ();
40
+ }
41
+
42
+ // printf("finally iCount:%d\r\n", iCount);
43
+ int x = iCount.load (memory_order_relaxed);
44
+ printf (" finally iCount:%d\r\n " , x);
45
+ }
46
+
47
+
48
+ // g++ -std=c++11 -pthread -o out atomictest.cpp && ./out
49
+ iCount:-4
50
+ iCount:-3
51
+ iCount:-2
52
+ iCount:-1
53
+ finally iCount:0
You can’t perform that action at this time.
0 commit comments