You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
34 lines
675 B
34 lines
675 B
#include <thread>
|
|
#include <fmt/core.h>
|
|
#include <chrono>
|
|
#include <iostream>
|
|
#include <thread>
|
|
#include <utility>
|
|
#include <iostream>
|
|
#include <mutex>
|
|
|
|
using namespace std::chrono_literals;
|
|
|
|
std::atomic_int counter = 0;
|
|
std::mutex counter_mutex;
|
|
|
|
|
|
void locked_counter() {
|
|
for (int i = 0; i < 5; ++i)
|
|
{
|
|
std::lock_guard<std::mutex> lock(counter_mutex);
|
|
std::this_thread::sleep_for(100ms);
|
|
std::cout << "Thread 1 executing\n";
|
|
++counter;
|
|
}
|
|
}
|
|
|
|
int main()
|
|
{
|
|
std::jthread t2(locked_counter); // pass by value
|
|
|
|
for(int i = 0; i < 5; ++i) {
|
|
std::lock_guard<std::mutex> lock(counter_mutex);
|
|
std::cout << "counter is " << counter << std::endl;
|
|
}
|
|
}
|
|
|