Commit a7b17ae118aa5ad57f5b5fe375e8ab89faced0d6

Authored by Grzegorz Jabłoński
1 parent 307a647f

Parially converted RAII mutex example to C++

examples07/03-raii/threads1.cpp
1 #include <stdio.h> 1 #include <stdio.h>
  2 +#include <thread>
2 #include "mutex.h" 3 #include "mutex.h"
3 4
4 -volatile int Counter=0; 5 +int Counter=0;
5 6
6 7
7 -void *  
8 -thread1 (void *p) 8 +void
  9 +thread1 ()
9 { 10 {
10 for (unsigned int i = 0; i < 100000; i++) 11 for (unsigned int i = 0; i < 100000; i++)
11 { 12 {
12 Counter++; 13 Counter++;
13 Counter--; 14 Counter--;
14 } 15 }
15 - pthread_exit (p);  
16 } 16 }
17 17
18 -void *  
19 -thread2 (void *p) 18 +void
  19 +thread2 ()
20 { 20 {
21 for (unsigned int i = 0; i < 100000; i++) 21 for (unsigned int i = 0; i < 100000; i++)
22 { 22 {
23 Counter++; 23 Counter++;
24 Counter--; 24 Counter--;
25 } 25 }
26 - pthread_exit (p);  
27 } 26 }
28 27
29 28
30 int 29 int
31 main () 30 main ()
32 { 31 {
33 - pthread_t t1;  
34 - pthread_t t2; 32 + std::thread t1(thread1);
  33 + std::thread t2(thread2);
35 34
36 - pthread_create (&t1, NULL, thread1, NULL);  
37 - pthread_create (&t2, NULL, thread2, NULL);  
38 -  
39 - pthread_join (t1, (void **) NULL);  
40 - pthread_join (t2, (void **) NULL); 35 + t1.join ();
  36 + t2.join ();
41 37
42 printf ("Counter=%d\n", Counter); 38 printf ("Counter=%d\n", Counter);
43 } 39 }
examples07/03-raii/threads2.cpp
1 #include <stdio.h> 1 #include <stdio.h>
  2 +#include <thread>
2 #include "mutex.h" 3 #include "mutex.h"
3 4
4 -volatile int Counter=0;  
5 -  
6 Mutex m; 5 Mutex m;
7 6
8 -void *  
9 -thread1 (void *p) 7 +int Counter=0;
  8 +
  9 +void
  10 +thread1 ()
10 { 11 {
11 for (unsigned int i = 0; i < 100000; i++) 12 for (unsigned int i = 0; i < 100000; i++)
12 { 13 {
@@ -14,11 +15,10 @@ thread1 (void *p) @@ -14,11 +15,10 @@ thread1 (void *p)
14 Counter++; 15 Counter++;
15 Counter--; 16 Counter--;
16 } 17 }
17 - pthread_exit (p);  
18 } 18 }
19 19
20 -void *  
21 -thread2 (void *p) 20 +void
  21 +thread2 ()
22 { 22 {
23 for (unsigned int i = 0; i < 100000; i++) 23 for (unsigned int i = 0; i < 100000; i++)
24 { 24 {
@@ -26,21 +26,17 @@ thread2 (void *p) @@ -26,21 +26,17 @@ thread2 (void *p)
26 Counter++; 26 Counter++;
27 Counter--; 27 Counter--;
28 } 28 }
29 - pthread_exit (p);  
30 } 29 }
31 30
32 31
33 int 32 int
34 main () 33 main ()
35 { 34 {
36 - pthread_t t1;  
37 - pthread_t t2;  
38 -  
39 - pthread_create (&t1, NULL, thread1, NULL);  
40 - pthread_create (&t2, NULL, thread2, NULL); 35 + std::thread t1(thread1);
  36 + std::thread t2(thread2);
41 37
42 - pthread_join (t1, (void **) NULL);  
43 - pthread_join (t2, (void **) NULL); 38 + t1.join ();
  39 + t2.join ();
44 40
45 printf ("Counter=%d\n", Counter); 41 printf ("Counter=%d\n", Counter);
46 } 42 }