New answers tagged multithreading
3
Don’t overthink the plumbing
With no disrespect to Mr. O’Dwyer, I think he missed something key going on here. std::call_once is the best tool for the job… if you’re really only calling some code once.
But your code includes a reset() function. That immediately invalidates the whole idea of std::call_once (and, by extension, std::once_flag). call_once means “...
4
Use std::once_flag
The std::once_flag class basically does what you want. However, there is no way nice way to reset it, except by using a trick like placement new, or by allocating a flag dynamically, and using a std::unique_ptr to point to it for example. As indi mentioned, it's not really "once" anymore then, but it does work for your specific ...
1
I have just one suggestion but you should evaluate in terms of performance. What I mean is that you should do a performance test with your current code and then with the new changes proposed to see if you gain.
You are using a lock() function inside the notify_all function.
void notify_all(const Message&... msg_) noexcept
{
auto l = lock();
// ...
5
Very good design! And very clean code. As-is, there’s very little I can recommend to improve things. In fact, the only code suggestions I can come up with off the top of my head are:
You should probably take all arguments in the callbacks (and notify function) by const&. That allows you to pass more complicated (and even non-copyable) types to callback ...
1
Each branch in simulate's if/else if/else block does pos += facing;. The DRY principle mandates lifting it out. After that the if branch becomes empty:
int val = zeroto3(rng);
if (val <= 1) {
}
else if (val == 2) {
stepCount++;
}
else {
stepCount++;
facing = -facing;
}
pos += facing;
This is a ...
2
Answers to your questions
Is the threading done safetly here? Is there any big no-nos here?
Avoid manually calling .lock() and .unlock(), and use the version of std::condition_variable::wait() that takes a predicate to wait for. Furthermore, you want to avoid needing locks. Instead of having threads update shared variables, consider having them store their ...
Top 50 recent answers are included
Related Tags
multithreading × 1448java × 444
c++ × 342
c# × 327
thread-safety × 231
python × 166
performance × 156
c++11 × 131
concurrency × 109
c × 68
queue × 63
locking × 60
python-3.x × 58
.net × 57
socket × 49
producer-consumer × 48
asynchronous × 45
beginner × 44
pthreads × 35
algorithm × 34
object-oriented × 33
lock-free × 31
android × 30
networking × 28
c++14 × 26