|
7 | 7 |
|
8 | 8 | struct GlobalData |
9 | 9 | { |
10 | | - std::map<int, int> g_fd_to_file; |
11 | | - PthreadRwMutex g_file_to_shadowzip_mutex; |
| 10 | + std::map<int, int> g_fd_to_file; |
| 11 | + PthreadRwMutex g_file_to_shadowzip_mutex; |
12 | 12 | }; |
13 | 13 | #define g_global_data (LeakSingleton<GlobalData, 0>::instance()) |
14 | 14 |
|
15 | | -int count; |
| 15 | +int a = 0; |
| 16 | +int b = 0; |
| 17 | +int c = 0; |
| 18 | +int d = 0; |
16 | 19 | const size_t THREAD_NUM = 6; |
17 | 20 |
|
18 | 21 | void increment_count() |
19 | 22 | { |
20 | | - { |
21 | | - PthreadWriteGuard guard(g_global_data->g_file_to_shadowzip_mutex); |
22 | | - count = count + 1; |
23 | | - std::cout << "write count:" << count << std::endl; |
24 | | - } |
| 23 | + PthreadWriteGuard guard(g_global_data->g_file_to_shadowzip_mutex); |
| 24 | + a++; |
| 25 | + b++; |
| 26 | + c++; |
| 27 | + d++; |
25 | 28 | } |
26 | 29 |
|
27 | | -long long get_count() |
| 30 | +void verify_count() |
28 | 31 | { |
29 | | - long long c; |
30 | | - { |
31 | | - PthreadReadGuard guard(g_global_data->g_file_to_shadowzip_mutex); |
32 | | - c = count; |
33 | | - std::cout << "read count:" << count << std::endl; |
34 | | - } |
35 | | - return (c); |
| 32 | + PthreadReadGuard guard(g_global_data->g_file_to_shadowzip_mutex); |
| 33 | + if (a != b || a != c || a != d) { |
| 34 | + std::cout << "pthread unit test failed: " << a << " " << b << " " << c << " " << d << std::endl; |
| 35 | + } |
36 | 36 | } |
37 | 37 |
|
38 | 38 | //----------------------------------------------------------------------- |
39 | 39 | void *thread_proc(void *arg) |
40 | 40 | { |
| 41 | + int thread_id = (int) (intptr_t) arg; |
| 42 | + std::cout << "thread " << thread_id << " started" << std::endl; |
41 | 43 | for(int i = 0; i < 1000000; i++){ |
42 | | - increment_count(); |
43 | | - get_count(); |
44 | | - } |
45 | | - |
| 44 | + increment_count(); |
| 45 | + verify_count(); |
| 46 | + } |
| 47 | + std::cout << "thread " << thread_id << " end" << std::endl; |
46 | 48 | pthread_exit(0); |
47 | 49 | return 0; |
48 | 50 | } |
49 | 51 |
|
50 | 52 | int main(int argc, char *argv[]) |
51 | 53 | { |
52 | | - LeakSingleton<GlobalData, 0>::init(); |
| 54 | + LeakSingleton<GlobalData, 0>::init(); |
53 | 55 | pthread_t threadids[THREAD_NUM]; |
54 | 56 | for(size_t i = 0; i < THREAD_NUM; i++) |
55 | 57 | { |
|
0 commit comments