C++ features by examples
Collaboration diagram for Threads:

Functions

void condition_variable_11 ()
 
void threads_11 ()
 
void mutex_11 ()
 

Detailed Description

threads

Function Documentation

◆ condition_variable_11()

void condition_variable_11 ( )

https://en.cppreference.com/w/cpp/thread/condition_variable

Definition at line 572 of file 11.cpp.

573{
574 mutex m;
575 bool ready;
576 condition_variable cv;
577 thread initiator([&m, &ready, &cv] {
578 unique_lock<mutex> lk(m);
579 lento();
580 lk.unlock();
581 ready = true;
582 cv.notify_one();
583 });
584 unique_lock<mutex> lk(m);
585 cv.wait(lk, [&ready] {return ready;});
586 initiator.join();
587}
Here is the caller graph for this function:

◆ mutex_11()

void mutex_11 ( )

Definition at line 632 of file 11.cpp.

633{
634 int unguarded = 0, guarded = 0;
635 mutex m;
636
637 thread t1([&unguarded, &guarded, &m]{
638 unguarded = lento(unguarded) + 1;
639
640 lock_guard<mutex> guard(m);
641 guarded = lento(guarded) + 1;
642 });
643 thread t2([&unguarded, &guarded, &m]{
644 unguarded = lento(unguarded) + 1;
645
646 lock_guard<mutex> guard(m);
647 guarded = lento(guarded) + 1;
648 });
649
650 assert(unguarded == 0);
651 assert(guarded == 0);
652 t1.join();
653 t2.join();
654 assert(unguarded == 1);
655 assert(guarded == 2);
656}
Here is the caller graph for this function:

◆ threads_11()

void threads_11 ( )

Definition at line 589 of file 11.cpp.

590{
591 this_thread::yield();
592 this_thread::get_id();
593 this_thread::sleep_for(chrono::nanoseconds(1));
594 promise<int> p;
595 future<int> f = p.get_future();
596 int v = 0;
597 thread t([&p, &v]{
598 lento();
599 p.set_value(2);
600 v = 3;
601 });
602 assert(v == 0);
603 assert(f.get() == 2);
604 lento();
605 assert(v == 3);
606 thread t2;
607 t2.swap(t);
608 assert(!t.joinable());
609 assert(t2.joinable());
610 t2.join();
611 try {
612 t2.join();
613 t2.detach();
614 } catch(const system_error& e) {
615 assert(e.code().value() == 22);
616 }
617 assert(!t2.joinable());
618
619 // detach demo
620 {
621 thread t3([&p, &v]{
622 v = 4;
623 });
624 t3.detach();
625 }
626 lento();
627 assert(v == 4);
628
630}
void condition_variable_11()
Definition: 11.cpp:572
Here is the call graph for this function:
Here is the caller graph for this function: