Skip to content

Commit

Permalink
example: add mutexes
Browse files Browse the repository at this point in the history
  • Loading branch information
conr2d committed Jun 21, 2022
1 parent 52bada8 commit 367bca6
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 0 deletions.
1 change: 1 addition & 0 deletions examples/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@ add_executable(channel-directions channel-directions.cpp)
add_executable(select select.cpp)
add_executable(non-blocking-channel-operations non-blocking-channel-operations.cpp)
add_executable(waitgroups waitgroups.cpp)
add_executable(mutexes mutexes.cpp)
add_executable(defer defer.cpp)
81 changes: 81 additions & 0 deletions examples/mutexes.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
// package main
//
// import (
// "fmt"
// "sync"
// )
//
// type Container struct {
// mu sync.Mutex
// counters map[string]int
// }
//
// func (c *Container) inc(name string) {
//
// c.mu.Lock()
// defer c.mu.Unlock()
// c.counters[name]++
// }
//
// func main() {
// c := Container{
// counters: map[string]int{"a": 0, "b": 0},
// }
//
// var wg sync.WaitGroup
//
// doIncrement := func(name string, n int) {
// for i := 0; i < n; i++ {
// c.inc(name)
// }
// wg.Done()
// }
//
// wg.Add(3)
// go doIncrement("a", 10000)
// go doIncrement("a", 10000)
// go doIncrement("b", 10000)
//
// wg.Wait()
// fmt.Println(c.counters)
// }

#include <eo/fmt.h>
#include <eo/sync.h>

using namespace eo;

struct Container {
std::mutex mu;
std::map<std::string, int> counters;

void inc(const std::string& name) {
std::scoped_lock g{mu};
counters[name]++;
}
};

func<> eo_main() {
auto c = Container{
.counters = {{"a", 0}, {"b", 0}},
};

auto wg = sync::WaitGroup();

auto do_increment = [&](const std::string& name, int n) {
for (auto i = 0; i < n; i++) {
c.inc(name);
}
wg.done();
};

wg.add(3);
go([&]() { do_increment("a", 10000); });
go([&]() { do_increment("a", 10000); });
go([&]() { do_increment("b", 10000); });

wg.wait();
fmt::println(c.counters);

co_return;
}

0 comments on commit 367bca6

Please sign in to comment.