std::unique_lock::lock

1
void lock();
(since C++11)

Locks the associated mutex. Effectively calls mutex()->lock().

Parameters

(none).

Return value

(none).

Exceptions

Example

The following example uses lock to re-acquire a mutex that was unlocked.

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
#include <mutex>
#include <thread>
#include <iostream>
#include <vector>
#include <chrono>
  
int main()
{
    int counter = 0;
    std::mutex counter_mutex;
    std::vector<std::thread> threads;
  
    auto worker_task = [&](int id) {
        std::unique_lock<std::mutex> lock(counter_mutex);
        ++counter;
        std::cout << id << ", initial counter: " << counter << '\n';
        lock.unlock();
  
        // don't hold the lock while we simulate an expensive operation
        std::this_thread::sleep_for(std::chrono::seconds(1));
  
        lock.lock();
        ++counter;
        std::cout << id << ", final counter: " << counter << '\n';
    };
  
    for (int i = 0; i < 10; ++i) threads.emplace_back(worker_task, i);
  
    for (auto &thread : threads) thread.join();
}

Possible output:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
0, initial counter: 1
1, initial counter: 2
2, initial counter: 3
3, initial counter: 4
4, initial counter: 5
5, initial counter: 6
6, initial counter: 7
7, initial counter: 8
8, initial counter: 9
9, initial counter: 10
6, final counter: 11
3, final counter: 12
4, final counter: 13
2, final counter: 14
5, final counter: 15
0, final counter: 16
1, final counter: 17
7, final counter: 18
9, final counter: 19
8, final counter: 20

See also

tries to lock the associated mutex, returns if the mutex is not available
(public member function)
unlocks the associated mutex
(public member function)
doc_CPP
2025-01-10 15:47:30
Comments
Leave a Comment

Please login to continue.