-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstd_mutex.cpp
101 lines (81 loc) · 1.57 KB
/
std_mutex.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/*
* =====================================================================================
*
* Filename: Mutex.cpp
*
* Description:
*
* Version: 1.0
* Created: 2016年01月18日 14时23分02秒
* Last Modified: 2017-12-31 12:30:49
* Revision: none
* Compiler: gcc
*
* Author: zt (),
* Organization:
*
* =====================================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
#include <thread>
#include <mutex>
#include <chrono>
#include <sys/syscall.h>
class TestData
{
public:
TestData()
{
d = 0;
}
~TestData()
{
}
public:
uint8_t d;
};
volatile int count = 0;
std::mutex mtx;
void attempt_10k_increases ()
{
for ( int i = 0; i < 10000; ++i )
{
if ( mtx.try_lock() )
{
++count;
mtx.unlock();
}
}
}
#if 0
void print_block ( int n, char c )
{
mtx.lock();
for ( int i = 0; i < n ; ++i )
std::cout << c;
std::cout << " " << syscall ( SYS_gettid ) << std::endl;
mtx.unlock();
}
#endif
int main ( int argc, char* argv[] )
{
( void ) argc;
( void ) argv;
#if 0
std::thread ( print_block, 30, '*' ).detach();
std::thread ( print_block, 30, '#' ).detach();
std::this_thread::sleep_for ( std::chrono::seconds ( 1 ) );
#endif
std::thread threads[10];
for ( int i = 0; i < 10 ; ++i )
{
threads[i] = std::thread ( attempt_10k_increases );
threads[i].detach();
}
sleep ( 1 );
std::cout << count << std::endl;
return 0;
}