Skip to content

Commit a3d281f

Browse files
authored
minor fixes - shared_lock, std::ref param to thread (#9)
* creating threads use the apt function * std::ref can't work on const rvalue use of deleted function ‘void std::ref(const _Tp&&) [with _Tp = int]’ invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’ * shared_lock uses shared_mutex
1 parent ed210a4 commit a3d281f

File tree

1 file changed

+7
-5
lines changed

1 file changed

+7
-5
lines changed

C++/07 C++ - Threading and Concurrency.md

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -104,8 +104,8 @@ There are several ways to create a thread:
104104
#include <thread>
105105

106106
// Define a function and start a thread that runs that function
107-
void rawr(param) {}
108-
std::thread rawr_thread(foo, params);
107+
void rawr(params) {}
108+
std::thread rawr_thread(rawr, params);
109109
```
110110
**Lambda Function**
111111
```c++
@@ -180,7 +180,8 @@ Example:
180180
```c++
181181
void ref_function(int &a, int b) {}
182182

183-
std::thread ref_function_thread(ref_function, std::ref(1), 2);
183+
int val;
184+
std::thread ref_function_thread(ref_function, std::ref(val), 2);
184185
```
185186
186187
**Because the thread functions can't return anything, passing by reference is the only way to properly get data out of a thread without using global variables.** Ensure that your thread modifies the data passed in by reference and you should be good to go.
@@ -480,7 +481,8 @@ A shared lock is just like a unique lock, except the lock is a shared lock as op
480481
- You can also use **nifty lock methods!**
481482

482483
```c++
483-
std::shared_lock<std::mutex> guard(my_mutex);
484+
std::shared_lock my_mutex;
485+
std::shared_lock<std::shared_mutex> guard(my_mutex);
484486

485487
// Check if guard owns lock (either works)
486488
guard.owns_lock();
@@ -497,7 +499,7 @@ If you defer the locks, you can use the **nifty lock methods!**
497499
498500
```c++
499501
// Initialise the lock guard, but don't actually lock yet
500-
std::shared_lock<std::mutex> guard(mutex_1, std::defer_lock);
502+
std::shared_lock<std::shared_mutex> guard(mutex_1, std::defer_lock);
501503
502504
// Now you can do some of the following!
503505
guard.lock(); // Lock now!

0 commit comments

Comments
 (0)