|
138 | 138 | ### `std::recursive_timed_mutex` 介绍 ### |
139 | 139 |
|
140 | 140 | 和 `std:recursive_mutex` 与 `std::mutex` 的关系一样,`std::recursive_timed_mutex` 的特性也可以从 `std::timed_mutex` 推导出来,感兴趣的同鞋可以自行查阅。;-) |
| 141 | + |
| 142 | +### std::lock_guard 介绍 ### |
| 143 | + |
| 144 | +与 Mutex RAII 相关,方便线程对互斥量上锁。例子([参考](http://www.cplusplus.com/reference/mutex/lock_guard/)): |
| 145 | + |
| 146 | + #include <iostream> // std::cout |
| 147 | + #include <thread> // std::thread |
| 148 | + #include <mutex> // std::mutex, std::lock_guard |
| 149 | + #include <stdexcept> // std::logic_error |
| 150 | + |
| 151 | + std::mutex mtx; |
| 152 | + |
| 153 | + void print_even (int x) { |
| 154 | + if (x%2==0) std::cout << x << " is even\n"; |
| 155 | + else throw (std::logic_error("not even")); |
| 156 | + } |
| 157 | + |
| 158 | + void print_thread_id (int id) { |
| 159 | + try { |
| 160 | + // using a local lock_guard to lock mtx guarantees unlocking on destruction / exception: |
| 161 | + std::lock_guard<std::mutex> lck (mtx); |
| 162 | + print_even(id); |
| 163 | + } |
| 164 | + catch (std::logic_error&) { |
| 165 | + std::cout << "[exception caught]\n"; |
| 166 | + } |
| 167 | + } |
| 168 | + |
| 169 | + int main () |
| 170 | + { |
| 171 | + std::thread threads[10]; |
| 172 | + // spawn 10 threads: |
| 173 | + for (int i=0; i<10; ++i) |
| 174 | + threads[i] = std::thread(print_thread_id,i+1); |
| 175 | + |
| 176 | + for (auto& th : threads) th.join(); |
| 177 | + |
| 178 | + return 0; |
| 179 | + } |
| 180 | + |
| 181 | +### `std::unique_lock` 介绍 ### |
| 182 | + |
| 183 | +与 Mutex RAII 相关,方便线程对互斥量上锁,但提供了更好的上锁和解锁控制。例子([参考](http://www.cplusplus.com/reference/mutex/unique_lock/)): |
| 184 | + |
| 185 | + #include <iostream> // std::cout |
| 186 | + #include <thread> // std::thread |
| 187 | + #include <mutex> // std::mutex, std::unique_lock |
| 188 | + |
| 189 | + std::mutex mtx; // mutex for critical section |
| 190 | + |
| 191 | + void print_block (int n, char c) { |
| 192 | + // critical section (exclusive access to std::cout signaled by lifetime of lck): |
| 193 | + std::unique_lock<std::mutex> lck (mtx); |
| 194 | + for (int i=0; i<n; ++i) { |
| 195 | + std::cout << c; |
| 196 | + } |
| 197 | + std::cout << '\n'; |
| 198 | + } |
| 199 | + |
| 200 | + int main () |
| 201 | + { |
| 202 | + std::thread th1 (print_block,50,'*'); |
| 203 | + std::thread th2 (print_block,50,'$'); |
| 204 | + |
| 205 | + th1.join(); |
| 206 | + th2.join(); |
| 207 | + |
| 208 | + return 0; |
| 209 | + } |
0 commit comments