看如下三段代码:
// mutex example
#include // std::cout
#include // std::thread
#include // std::mutex
std::mutex mtx; // mutex for critical section
void print_block (int n, char c) {
// critical section (exclusive access to std::cout signaled by locking mtx):
mtx.lock();
for (int i=0; i
#include
#include
#include
int v = 1;
void critical_section(int change_v) {
static std::mutex mtx;
std::lock_guard lock(mtx);
// do contention operations
v = change_v;
// mtx will be destructed when exit this region
}
int main() {
std::thread t1(critical_section, 2), t2(critical_section, 3);
t1.join();
t2.join();
std::cout << v << std::endl;
return 0;
}
#include
#include
#include
int v = 1;
void critical_section(int change_v) {
static std::mutex mtx;
std::unique_lock lock(mtx);
// do contention operations
v = change_v;
std::cout << v << std::endl;
// release the lock
lock.unlock();
// during this period,
// others are allowed to acquire v
// start another group of contention operations
// lock again
lock.lock();
v += 1;
std::cout << v << std::endl;
}
int main() {
std::thread t1(critical_section, 2), t2(critical_section, 3);
t1.join();
t2.join();
return 0;
}
尝试编译无果……
查一下,c++20应该可以。
只能使用如下链接:
coliru.stacked-crooked.com
01
02
03
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)