Latest / CyberSecurity Summary / Concurrency with Modern C++: What every professional C++ programmer should know about concurrency
Transcript
- 0:00Speaker 1: Welcome to the deep dive. We've got some really interesting
- 0:02Speaker 1: material you sent over on concurrency in modern C plus
- 0:06Speaker 1: plus POM. Looks like it's mostly drawing from the book
- 0:09Speaker 1: Concurrency with Modern C plus plus POM.
- 0:11Speaker 2: That's right, And our goal today is well, to unpack
- 0:15Speaker 2: the core ideas, maybe find some of those aha moments
- 0:19Speaker 2: for you.
- 0:20Speaker 1: Yeah, make this whole complex topic a bit more accessible
- 0:23Speaker 1: without drowning in the jargon exactly.
- 0:25Speaker 2: And you know, the book itself kind of hints at
- 0:27Speaker 2: the challenge. It mentions how the C plus plus memory
- 0:30Speaker 2: model often runs counter to our intuition.
- 0:33Speaker 1: Oh. Interesting, So that's our mission then, to navigate that
- 0:37Speaker 1: complexity and pull out the essentials you need for writing
- 0:40Speaker 1: you know, solid concurrency.
- 0:41Speaker 2: Plus plus code, precisely efficient, dependable code. That's the end.
- 0:46Speaker 1: Okay, let's get started then, right at the foundation the
- 0:49Speaker 1: memory model. Yeah, in simple terms, what is it we're
- 0:51Speaker 1: trying to wrap our heads around here.
- 0:53Speaker 2: Well, think of the memory model as like the official
- 0:56Speaker 2: rule book. It dictates how different threads in your program
- 0:59Speaker 2: see and interact with the computer's memory.
- 1:01Speaker 1: Okay, rules for memory interaction.
- 1:03Speaker 2: And from a concurrency angle, two basic questions pop up. First,
- 1:07Speaker 2: what counts as a single place in memory a memory location.
- 1:11Speaker 1: Right, is it a bite an integer?
- 1:14Speaker 2: According to the source, Yeah, it's either a basic scaler
- 1:16Speaker 2: type like your ince floats, pointers, enoms, or if you
- 1:20Speaker 2: have bitfields, it's the largest sort of continuous sequence of
- 1:24Speaker 2: those bits.
- 1:25Speaker 1: Got it. Scaler types are contiguous bitfields. What was the
- 1:28Speaker 1: second question?
- 1:28Speaker 2: Ah, the big one. What happens when multiple threads try
- 1:32Speaker 2: to access that same memory location around.
- 1:35Speaker 1: The same time. Okay, and I sense danger here?
- 1:37Speaker 2: You got it? That leads us straight to data races. Okay,
- 1:40Speaker 2: imagine two threads hitting the same shared variable. It's mutable,
- 1:44Speaker 2: and at least one of those threads is trying to
- 1:46Speaker 2: write to it.
- 1:46Speaker 1: That's data race.
- 1:47Speaker 2: That's the data race, and the result undefined behavior. Ah,
- 1:51Speaker 2: the dreaded ub exactly the wild West. Your program might crash,
- 1:56Speaker 2: spit out garbage, or maybe even seem to work fine
- 1:59Speaker 2: for a while, then just fail later completely out of
- 2:01Speaker 2: the blue.
- 2:02Speaker 1: So that's why we need things like mute texts and locks. Yeah,
- 2:04Speaker 1: to coordinate who gets access when precisely.
- 2:07Speaker 2: There are the traffic cops for shared data access essential tools.
- 2:11Speaker 1: The book uses thread safe singleton initialization as a classic example.
- 2:16Speaker 1: Why is that such a good illustration. It seems simple, right,
- 2:19Speaker 1: just one instance.
- 2:20Speaker 2: Well, it seems simple in a single thread, but imagine
- 2:23Speaker 2: multiple threads all deciding, hey, I need the singleton at
- 2:27Speaker 2: the exact same time.
- 2:28Speaker 1: Ah. So if they all check and see it doesn't
- 2:30Speaker 1: exist yet, they.
- 2:31Speaker 2: Might all try to create it, and suddenly you've got
- 2:33Speaker 2: multiple singletons, which completely breaks the whole idea.
- 2:36Speaker 1: Right, So, thread safe techniques make sure only one thread
- 2:39Speaker 1: actually does the creation, even if many try.
- 2:42Speaker 2: Exactly ensure as it's created exactly once.
- 2:45Speaker 1: Now for digging deeper, the book mentions a tool called creepmem.
- 2:49Speaker 1: What's that about?
- 2:49Speaker 2: Oh, CRIPPYMM is fantastic for this. It's like a sandbox
- 2:54Speaker 2: or a simulator for the C plus plus memory model.
- 2:57Speaker 1: Okay.
- 2:57Speaker 2: You feed it small snippets of concurrent code, and it
- 3:00Speaker 2: shows you all the possible ways the operations from different
- 3:03Speaker 2: threads could interleave. It visualizes the impact of different memory orderings.
- 3:07Speaker 1: So you can actually see how things might go wrong
- 3:09Speaker 1: or why a certain ordering works precisely.
- 3:12Speaker 2: It helps build that intuition for how the memory model behaves, which,
- 3:16Speaker 2: as we said, isn't always obvious.
- 3:17Speaker 1: Really valuable tool, okay, memory model basics covered, let's talk
- 3:21Speaker 1: about the threads themselves. We've had std dot thread for
- 3:24Speaker 1: a while clus plus twenty added std dot j thread.
- 3:28Speaker 1: What's the leap forward there?
- 3:29Speaker 2: The big difference really is resource management safety.
- 3:32Speaker 1: Also with sdd.
- 3:34Speaker 2: Dot thread, you the programmer must remember to either join
- 3:38Speaker 2: the thread, wait for it to finish, or detach it
- 3:40Speaker 2: to run independently.
- 3:41Speaker 1: And if you forget, if the std.
- 3:43Speaker 2: Dot thread object gets destroyed before you do either, your
- 3:45Speaker 2: program terminates. It's a common mistake.
- 3:48Speaker 1: Ouch. Okay, So how does std dot j thread fix that.
- 3:51Speaker 2: It's our Aii based resource acquisition is initialization. When an
- 3:55Speaker 2: std dot j thread object goes out of scope, its
- 3:58Speaker 2: destructor automatically calls joint.
- 4:00Speaker 1: No more forgetting Nice. That sounds much safer it is.
- 4:03Speaker 2: Plus, std dot j thread has built in support for
- 4:06Speaker 2: cooperative interruption, a clean way to ask a thread to stop.
- 4:09Speaker 1: Okay, cooperative interruption. We'll probably circle back to that now.
- 4:12Speaker 1: The book mentioned something tricky with std dot shared ptr.
- 4:16Speaker 1: I thought they were threads safe.
- 4:17Speaker 2: They help with memory management in threads. Yes, they prevent
- 4:21Speaker 2: leaks by managing the object's lifetime automatically, but the shared
- 4:25Speaker 2: pointer itself isn't fully thread safe for all operations.
- 4:28Speaker 1: What's the catch?
- 4:28Speaker 2: It's the internal reference counter. If you have multiple threads
- 4:31Speaker 2: all trying to say, assign a new shared pointer to
- 4:34Speaker 2: the same shared pointer variable, especially if it was passed
- 4:37Speaker 2: by reference, we could corrupt the count exactly. You can
- 4:40Speaker 2: get a data RaSE on that internal counter. The book
- 4:43Speaker 2: shows an example where this happens when threads modify a
- 4:45Speaker 2: shared shared ptr passed by reference. The object being pointed
- 4:50Speaker 2: to might be fine, but the pointer's bookkeeping gets messed up.
- 4:53Speaker 1: So if I need multiple threads to safely update which
- 4:56Speaker 1: object to shared pointer points to, what's the solution.
- 5:00Speaker 2: The book suggests using std dot atomic store for that
- 5:03Speaker 2: specific case to make the update atomic, but it also
- 5:06Speaker 2: points out that this is kind.
- 5:07Speaker 1: Of a workaround. What's the real fix? Then?
- 5:09Speaker 2: Ideally we'd use atomic smart pointers like std dot atomas
- 5:13Speaker 2: esdd dot shared ptr, which C plus plus twenty introduced
- 5:17Speaker 2: that handles the atomicity of the pointer operations themselves.
- 5:20Speaker 1: Okay, that makes sense. The book also mentioned std dot
- 5:23Speaker 1: atomic cref.
- 5:24Speaker 2: What's that for, ah, atomic cref. That's pretty neat. It
- 5:27Speaker 2: lets you perform atomic operations on an existing object that
- 5:31Speaker 2: wasn't originally declared. Std dot atomic, so you.
- 5:34Speaker 1: Can temporarily treat a regular variable as atomic sort of.
- 5:37Speaker 2: Yeah, you created an automic craft to it, and then
- 5:39Speaker 2: you can use atomic operations like fetchad or compare exchange
- 5:43Speaker 2: strong directly on that underlying variable through the reference. The
- 5:47Speaker 2: example showed incrementing a counter inside some big object without
- 5:50Speaker 2: needing locks or making the whole object atomic.
- 5:53Speaker 1: Interesting, so careful management is key. This leads us nicely
- 5:56Speaker 1: into memory ordering, sequential consistency, acquire release, relaxed. These sound
- 6:02Speaker 1: like different levels of rules.
- 6:03Speaker 2: They are. They're different contracts, different guarantees about how memory
- 6:06Speaker 2: operations become visible across threads.
- 6:09Speaker 1: Let's start with the strictest sequential consistency memory order.
- 6:13Speaker 2: Seconds, right, That's the default for atomics, and it's the
- 6:17Speaker 2: easiest to reason about it. Basically, guarantees two things. One,
- 6:21Speaker 2: all threads agree on a single global order of all
- 6:24Speaker 2: sequentially consistent operations, and two, the operations within any single
- 6:30Speaker 2: thread happen in the order you wrote them in your code.
- 6:33Speaker 1: Like one single timeline for everything.
- 6:35Speaker 2: Exactly simple model, but it can sometimes have performance costs
- 6:39Speaker 2: because the hardware has to work harder to maintain that
- 6:41Speaker 2: global order.
- 6:42Speaker 1: Okay, what about acchore release semantics. Then sounds like it
- 6:45Speaker 1: loosens things up a bit.
- 6:46Speaker 2: It does acquoire, release memory order, require memory order, release
- 6:51Speaker 2: memory order, roll, and also consume, though that's trickier. Focuses
- 6:55Speaker 2: on synchronization between operations on the same atomic.
- 6:58Speaker 1: Variable, same variable, okay.
- 7:00Speaker 2: Release operation. Typically a right ensures that all memory rights
- 7:03Speaker 2: that happen before it in the same thread become visible
- 7:07Speaker 2: to other threads that later perform an acquire operation usually
- 7:10Speaker 2: read on that same atomic variable.
- 7:13Speaker 1: So the release makes prior rights visible and the acquire
- 7:16Speaker 1: sees them precisely.
- 7:18Speaker 2: This creates what's called a synchronizes with relationship. It's fundamental.
- 7:23Speaker 2: The book points out this is how mutexes, thread joins,
- 7:26Speaker 2: condition variables, all the higher level stuff actually works under
- 7:29Speaker 2: the hood. A lock release synchronizes with a subsequent.
- 7:33Speaker 1: Lock acquire that synchronizes with it. Sounds important. It establishes
- 7:37Speaker 1: order across threads.
- 7:38Speaker 2: Yes, it establishes A happens before relationship. If action A
- 7:43Speaker 2: synchronizes with action B, then A happens before B. This
- 7:47Speaker 2: guarantees visibility of memory changes.
- 7:49Speaker 1: Got it? Now? What about the most lenient one memory
- 7:52Speaker 1: order relaxed? What guarantees do we lose there.
- 7:55Speaker 2: With relaxed ordering, you only get the bare minimum the
- 7:59Speaker 2: operation itself as atomic. It happens indivisibly, and there's a
- 8:02Speaker 2: single modification order for that specific atomic variable. All threads
- 8:06Speaker 2: will agree on the sequence of values written to that one.
- 8:08Speaker 1: Variable, but no guarantees about other memory operations exactly.
- 8:11Speaker 2: Relaxed operations don't create synchronizers with relationships. They don't guarantee
- 8:15Speaker 2: anything about the visibility or ordering of other reads and writes,
- 8:18Speaker 2: even to the same variable by different threads or to
- 8:21Speaker 2: different variables.
- 8:22Speaker 1: So potentially faster, but much harder to reason about, much harder.
- 8:26Speaker 2: The book shows using fetchad with relaxed ordering for a
- 8:29Speaker 2: simple counter, which is a common use case, but it
- 8:32Speaker 2: also warns that you can still get data rass on
- 8:35Speaker 2: non atomic variables even if you're reading related atomics with
- 8:38Speaker 2: relaxed order, because there's no happens before relationship established. It's
- 8:42Speaker 2: subtle stuff.
- 8:43Speaker 1: And where do memory fences? Atomic thread fens.
- 8:46Speaker 2: Fit in fences acts like barriers. They enforce ordering constraints
- 8:50Speaker 2: between operations before the fence and operations after the fence,
- 8:53Speaker 2: even across different variables or relaxed atomics. A release fence
- 8:57Speaker 2: makes prior rights visible to threads that later cute and
- 9:00Speaker 2: acquire fence. It's another way to establish that synchronizes with relationship,
- 9:05Speaker 2: but without needing a specific atomic variable to mediate.
- 9:08Speaker 1: Okay, that's a lot to digest on ordering. Let's shift
- 9:10Speaker 1: to actually using threads. How do we launch them? What
- 9:13Speaker 1: are the options?
- 9:13Speaker 2: The main way is std dot thread. Its constructor can
- 9:17Speaker 2: take basically any callable thing hollible thing. Yeah, like a
- 9:20Speaker 2: regular function pointer or a function object you know, an
- 9:24Speaker 2: object where you've overloaded the parentheses operator, or very commonly
- 9:29Speaker 2: a lambda function.
- 9:30Speaker 1: Right. Lambas are handy there.
- 9:31Speaker 2: Super handy. You just passed the function or lambda you
- 9:34Speaker 2: want to run in the new thread, followed by any
- 9:36Speaker 2: arguments it needs. The book shows a simple Hello from
- 9:39Speaker 2: thread using a lambda.
- 9:41Speaker 1: And once it's running, we have to decide what happens
- 9:44Speaker 1: when it finishes. Join or detach.
- 9:47Speaker 2: Exactly, You have to make a choice before the std
- 9:50Speaker 2: dot thread object itself is destroyed. Join means the current
- 9:54Speaker 2: thread waits right there until the launched thread completes.
- 9:58Speaker 1: Useful if you need its result or need to know
- 10:00Speaker 1: it's done before cleaning up resources.
- 10:02Speaker 2: Precisely. Detach. On the other hand, lets the thread run
- 10:05Speaker 2: completely independently in the background. The original thread continues immediately.
- 10:11Speaker 1: But that sounds risky. What if the detached thread needs
- 10:14Speaker 1: data that the original thread owns.
- 10:16Speaker 2: That's the big danger. If the original thread finishes and
- 10:18Speaker 2: its data goes out of scope, but the detached thread
- 10:21Speaker 2: is still running and tries to access that data, Boom,
- 10:25Speaker 2: undefined behavior again. So the book advises joining, usually strongly
- 10:29Speaker 2: advises joining, especially if the thread interacts with data whose
- 10:32Speaker 2: lifetime is tied to the scope where the thread was created.
- 10:35Speaker 2: Detaching requires very careful management of lifetimes.
- 10:39Speaker 1: Makes sense. What about std dot thread dot hardware concurrency.
- 10:43Speaker 2: It's said to us it gives you a hint, basically,
- 10:46Speaker 2: an estimate of how many threads the hardware can genuinely
- 10:49Speaker 2: run in parallel, often related to the number of CPU
- 10:53Speaker 2: cores or hyperthreads.
- 10:55Speaker 1: A hint, not a rule, definitely just a hint.
- 10:57Speaker 2: The optimal number of threads depends heavily on the specific task, io, contention,
- 11:01Speaker 2: et cetera. Using exactly this number isn't always best. The
- 11:05Speaker 2: book mentions, it's just a starting point, a native handle
- 11:08Speaker 2: that's an escape patch. It gives you direct access to
- 11:10Speaker 2: the underlying operating systems thread handle like a thread on
- 11:13Speaker 2: Linux or a handle on Windows. If you need to
- 11:16Speaker 2: do something platform specific that the C plus plus standard
- 11:18Speaker 2: library doesn't cover, use with caution though.
- 11:21Speaker 1: Okay, got it. Let's move on to the tools we
- 11:24Speaker 1: use with threads synchronization primitives, starting with the most basic
- 11:27Speaker 1: STD mutex.
- 11:29Speaker 2: Right, the mutex its core job is mutual exclusion, protecting
- 11:33Speaker 2: shared data.
- 11:34Speaker 1: How does it do that?
- 11:35Speaker 2: Think of it as a lock guarding a piece of data.
- 11:38Speaker 2: Before a thread can touch that data, it has to
- 11:40Speaker 2: lock the mutex. If another thread already holds the lock,
- 11:43Speaker 2: the first thread weights. Once it's done, it must unlock
- 11:47Speaker 2: the mutex, allowing another waiting thread to proceed.
- 11:50Speaker 1: So only one thread gets access at a time. Prevents
- 11:52Speaker 1: data rases on that protected data exactly.
- 11:55Speaker 2: Mutexes are your go to for protecting shared mutable state
- 11:58Speaker 2: first line of defense.
- 12:00Speaker 1: But the book warns about deadlocks. How did mutexes lead
- 12:04Speaker 1: to that?
- 12:05Speaker 2: Ah? The classic deadlock scenario. Imagine thread one locks mutex A,
- 12:09Speaker 2: then tries to lock mutex B. Simultaneously, Thread two locks
- 12:13Speaker 2: mutex B, then tries to lock mutex A.
- 12:15Speaker 1: Oh. Thread one has A and wants B. Thread two
- 12:18Speaker 1: has B and wants a.
- 12:19Speaker 2: And they're stuck. Neither can proceed because it's waiting for
- 12:22Speaker 2: the resource the other one holds. That's a deadlock. They
- 12:24Speaker 2: wait forever, masty.
- 12:26Speaker 1: How do we avoid that when we need multiple locks?
- 12:28Speaker 2: The standard solution is std dot lock. You pass it
- 12:31Speaker 2: all the mutexts you need to acquire. It uses a
- 12:34Speaker 2: deadlock avoidance algorithm internally to try and lock all of them.
- 12:37Speaker 1: Atomically atomically, meaning it gets all of them or none
- 12:40Speaker 1: of them.
- 12:40Speaker 2: Essentially. Yes, it guarantees it won't end up in a
- 12:43Speaker 2: state where it holds some locks while blocking waiting for
- 12:46Speaker 2: others in a way that contributes to deadlock. If it
- 12:49Speaker 2: can't get all locks, it'll release any it acquired and
- 12:51Speaker 2: try again, or perhaps throw an exception, depending on the context.
- 12:54Speaker 1: Okay, so std dot lock for multiple mutexes. Yeah, good tip.
- 12:59Speaker 1: We mentioned threads saf initialization earlier. Besides a simple lock.
- 13:02Speaker 1: What other techniques does the book cover?
- 13:04Speaker 2: Several good ones. If something can be a const expert,
- 13:06Speaker 2: its value is fixed at compile time, so that's inherently thread.
- 13:09Speaker 1: Safe, right, no runtime race possible.
- 13:11Speaker 2: Well, then there's std dotkalents with the std dot once flag.
- 13:16Speaker 2: You pass it a flag and a function like your
- 13:18Speaker 2: initialization function. The standard guarantees that function will be executed
- 13:22Speaker 2: exactly once by the first thread that calls it, even
- 13:25Speaker 2: if many threads call it concurrently, other threads will wait
- 13:28Speaker 2: until the first one is done.
- 13:29Speaker 1: Okay, that sounds robust.
- 13:30Speaker 2: Very Another common C plus plus idiom, especially since C
- 13:34Speaker 2: plus plus eleven, is the Meyers singleton. Using a static
- 13:39Speaker 2: variable inside a function.
- 13:40Speaker 1: Like static my singleton instance return.
- 13:43Speaker 2: Instance exactly that. The language guarantees that the initialization of
- 13:47Speaker 2: that static local variable is thread safe. The compiler and
- 13:51Speaker 2: runtime handle the locking implicitly. It's often the simplest and
- 13:55Speaker 2: preferred way.
- 13:56Speaker 1: Now simple as good any others.
- 13:59Speaker 2: Well of all, if your program structure allows it is
- 14:02Speaker 2: just initialize the shared resource in your main thread before
- 14:05Speaker 2: you create any other threads. No concurrency Doing initialization means
- 14:10Speaker 2: no problem?
- 14:11Speaker 1: Fair enough? What about signaling between threads, like, hey, the
- 14:14Speaker 1: data you're waiting for is ready. That's std dot condition
- 14:18Speaker 1: variable precisely.
- 14:19Speaker 2: Condition variables let threads weight efficiently until some condition becomes true.
- 14:23Speaker 1: How do they work? Do they need a mutex?
- 14:25Speaker 2: Yes? They always work together with the mutex. A waiting
- 14:28Speaker 2: thread must first lock the mutex protecting the shared state
- 14:31Speaker 2: at the condition. Then it calls weight on the condition variable,
- 14:35Speaker 2: and weight does what. It atomically releases the mutex and
- 14:38Speaker 2: puts the thread to sleep. It waits until another thread notifies.
- 14:42Speaker 1: It notifies it how by calling.
- 14:43Speaker 2: Notify one or notifile on the same condition variable. When
- 14:48Speaker 2: the waiting thread wakes up, it automatically reacquires the mutex
- 14:52Speaker 2: before weight returns.
- 14:54Speaker 1: Okay, it wakes up, gets the locked back. Then it
- 14:56Speaker 1: can check the condition exactly.
- 14:58Speaker 2: And this is crucial. It must check the condition again
- 15:01Speaker 2: after waking up.
- 15:02Speaker 1: Why didn't get notified because the condition is true.
- 15:05Speaker 2: Not necessarily, you can get spurious wakeups where the thread
- 15:08Speaker 2: wakes up even though no notification happen or the condition
- 15:10Speaker 2: changed back. That's why weight functions usually take a predicate,
- 15:14Speaker 2: a lambda or function that checks the actual condition. The
- 15:17Speaker 2: weight will only return if the predicate is true or
- 15:20Speaker 2: if interrupted.
- 15:21Speaker 1: Ah, so the predicate handles spurious wakeups. Never wait with
- 15:25Speaker 1: that one.
- 15:26Speaker 2: That's the rule. Always weight with the predicate.
- 15:28Speaker 1: Now C plus plus twenty brought cooperative interruption std dot
- 15:32Speaker 1: stop source stop token. How does that fit in? Especially
- 15:36Speaker 1: with j thread and condition.
- 15:38Speaker 2: Very blany right, This is a much better way to
- 15:40Speaker 2: ask threads to stop than say, just setting a boolean flag.
- 15:43Speaker 2: It's more integrated.
- 15:44Speaker 1: How does it work.
- 15:45Speaker 2: You create a std dot stop source. This object can
- 15:49Speaker 2: request that associated operations stop. From the stop source, you
- 15:53Speaker 2: get std dot stop tokens. You pass these tokens to
- 15:56Speaker 2: the threads or operations.
- 15:57Speaker 1: You might want to interrupt, and the thread checks up
- 16:00Speaker 1: the token.
- 16:00Speaker 2: Yes, a thread can periodically call stop requested on its token.
- 16:05Speaker 2: Or even better, many blocking functions, like the weight functions
- 16:08Speaker 2: on std dot condition variably needs, and the ones in
- 16:11Speaker 2: J thread implicitly can accept a stop token. They'll automatically
- 16:15Speaker 2: wake up if a stop is requested on that token.
- 16:17Speaker 1: So J thread uses this automatically.
- 16:19Speaker 2: J thread has a stop source built in. If you
- 16:21Speaker 2: create a J thread with a function that takes a
- 16:23Speaker 2: stop token as its first argument, the J threads destructor
- 16:26Speaker 2: will automatically request stop before joining. It makes graceful shut down.
- 16:30Speaker 1: Much easier and std dot stop call back that lets.
- 16:33Speaker 2: You register a function that gets called immediately when stop
- 16:36Speaker 2: is requested on a given token, useful for things like
- 16:39Speaker 2: quickly closing a socket or canceling an io operation.
- 16:42Speaker 1: Okay, a much cleaner stop mechanism. What about STD dot
- 16:45Speaker 1: counting semaphore also C plus plus twenty. How's that different
- 16:47Speaker 1: from a mutex?
- 16:48Speaker 2: A mutex is about exclusive access only one thread in
- 16:51Speaker 2: at a time. A semaphore maintains a counter representing available
- 16:55Speaker 2: resources or permits.
- 16:57Speaker 1: How does that work?
- 16:58Speaker 2: A thread calls a choir to take a permit, decrementing
- 17:01Speaker 2: the counter. If the counter is zero, the thread blocks.
- 17:05Speaker 2: A thread calls release to return a permit, incrementing the counter,
- 17:09Speaker 2: potentially waking up a blocked thread.
- 17:11Speaker 1: Can different threads acquire and release?
- 17:13Speaker 2: Yes, that's a key difference from utexas, which are usually
- 17:17Speaker 2: locked and unlocked by the same thread Somemophores are great
- 17:20Speaker 2: for controlling access to a pool of n resources or
- 17:23Speaker 2: for producer consumer scenarios where one thread signals another about
- 17:26Speaker 2: available work. They're thread agnostic.
- 17:29Speaker 1: Interesting. Lastly, for basic sinc C plus plus twenty also
- 17:33Speaker 1: give us STD dot barrier and std dot latch. Yeah,
- 17:36Speaker 1: coordinating multiple threads exactly.
- 17:38Speaker 2: Both are for synchronizing a group of threads at a
- 17:40Speaker 2: specific point.
- 17:41Speaker 1: What's the difference latch versus barrier.
- 17:43Speaker 2: A SSTD dot latch is basically a one shot countdown.
- 17:46Speaker 2: You initialize it with a count threads call countdown. When
- 17:48Speaker 2: the count reaches zero, any threads waiting on the latch
- 17:51Speaker 2: using weight are unblocked. After that, the latch is done.
- 17:54Speaker 2: It can't be reset.
- 17:55Speaker 1: One time use and a barrier.
- 17:58Speaker 2: A std dot barrier is reusable. You initialize it with
- 18:01Speaker 2: the number of threads in the group. Each thread calls
- 18:04Speaker 2: arrive and weight. When all threads have arrived, they are
- 18:07Speaker 2: all unblocked simultaneously. Crucially, the barrier resets ready for the
- 18:12Speaker 2: next synchronization phase. You can even run a completion function
- 18:16Speaker 2: when all threads arrive but before they're unblocked.
- 18:18Speaker 1: So latch for a single sync point barrier for repeated
- 18:22Speaker 1: phases of computation.
- 18:24Speaker 2: That's a good way to think about it. The book
- 18:25Speaker 2: shows an example of barriers being used across different stages
- 18:28Speaker 2: where the number of workers might even change.
- 18:30Speaker 1: Okay, let's move up a level to tasks and futures.
- 18:33Speaker 1: Std dot ASNC sounds really convenient for running stuff in
- 18:36Speaker 1: the background.
- 18:37Speaker 2: It is. It's a high level way to say, run
- 18:40Speaker 2: this function, possibly on another thread, and give me back
- 18:43Speaker 2: something I can use to get the result later.
- 18:45Speaker 1: That's something is the future exactly.
- 18:47Speaker 2: Std dot ACNC returns std dot future object, and it
- 18:50Speaker 2: handles the thread management, often using an internal.
- 18:53Speaker 1: Threadpool you mentioned, possibly on another thread right.
- 18:57Speaker 2: Std dot ACNC takes an optional launch policy. The default
- 19:01Speaker 2: std dot launch dot acing std dot launch dot deferred
- 19:04Speaker 2: usually runs it on a new thread eager evaluation. But
- 19:07Speaker 2: you can specify sdd dot launch dot acing to guarantee
- 19:10Speaker 2: a new thread, or std dot launch dot deferred to
- 19:13Speaker 2: make it.
- 19:14Speaker 1: Lazy lazy evaluation meaning.
- 19:16Speaker 2: Meaning the function only runs when you actually call get
- 19:19Speaker 2: or wait on the future it runs synchronously in the
- 19:22Speaker 2: thread that calls get.
- 19:23Speaker 1: Interesting trade off. What about std dot package task How
- 19:26Speaker 1: does that fit?
- 19:26Speaker 2: In std dot package task gives you more control. It
- 19:29Speaker 2: bundles up a function or callable with a promise the
- 19:32Speaker 2: thing that will eventually hold the result. Okay, it gives
- 19:34Speaker 2: you back at sdd dot future associated with that promise.
- 19:36Speaker 2: But crucially, the task doesn't run yet. You are responsible
- 19:40Speaker 2: for invoking the package task object itself, maybe passing it
- 19:43Speaker 2: to a thread you manage, or putting it in your
- 19:45Speaker 2: own queue for a threadpool.
- 19:47Speaker 1: So ACNC is fire and forget with a future back
- 19:50Speaker 1: package task is prepare and run later.
- 19:53Speaker 2: That's a good way to put it package. Task decouples
- 19:55Speaker 2: defining the work from executing it.
- 19:57Speaker 1: In std dot future itself. Yeah, just a placeholder for
- 20:00Speaker 1: the result pretty much.
- 20:02Speaker 2: It represents a result that will eventually be available from
- 20:05Speaker 2: some asynchronous operation. You call get on it to retrieve
- 20:10Speaker 2: the value those get block Yes. If the result isn't
- 20:13Speaker 2: ready yet, debt blocks the calling thread until it is. Also, importantly,
- 20:17Speaker 2: you can typically only call get once on a regular
- 20:21Speaker 2: sdd dot future.
- 20:22Speaker 1: The result is moved out only once. What if multiple
- 20:25Speaker 1: threads need the result?
- 20:27Speaker 2: Ah, that's where std dot shared future comes in. You
- 20:30Speaker 2: can create a shared future from a sdd dot future
- 20:32Speaker 2: which consumes the original future. Copies of the shared future
- 20:36Speaker 2: can then be given to multiple threads, and they can
- 20:38Speaker 2: all call get to retrieve a copy of the result
- 20:40Speaker 2: once it's ready.
- 20:41Speaker 1: Okay, so future for single result retrieval, shared future for
- 20:44Speaker 1: multiple correct. How do futures compared to condition variables for synchronization,
- 20:49Speaker 1: The book mentioned a comparison.
- 20:51Speaker 2: They serve different purposes. Mostly, conditioned variables are more general
- 20:54Speaker 2: purpose for complex waiting logic, maybe involving multiple conditions or
- 20:58Speaker 2: repeated signaling. Futures are primarily designed for getting a single
- 21:02Speaker 2: result back from a one off task.
- 21:04Speaker 1: So futures are simpler for the GATA result case.
- 21:07Speaker 2: Often yes, they bundle the data transmission, the result or
- 21:10Speaker 2: exception with the synchronization. With conditioned variables, you manage the
- 21:14Speaker 2: shared data and locking separately, which can be more error
- 21:17Speaker 2: prone if not done carefully. Tasks futures are often less
- 21:21Speaker 2: susceptible to issues like lost way cups.
- 21:23Speaker 1: Right DA, that makes sense. Let's switch gears to the
- 21:25Speaker 1: parallel algorithms in the SEL. Since C plus plus seventeen
- 21:28Speaker 1: many of them can run in parallel.
- 21:30Speaker 2: Yes, a huge addition. Many standard algorithms like four each, transform,
- 21:34Speaker 2: reduced sort, et cetera, now have overloads that take in
- 21:37Speaker 2: execution policy as the first argument.
- 21:39Speaker 1: Execution policy, what are the options?
- 21:41Speaker 2: The main ones are std dot execution dot SICK for
- 21:45Speaker 2: sequential execution, the old default std dot execution dot PR
- 21:49Speaker 2: for parallel execution on multiple threads, and std dot execution
- 21:53Speaker 2: dot PARENTSEC for parallel and potentially vectorized execution.
- 21:57Speaker 1: Vectorized like SIMD.
- 21:59Speaker 2: Exactly, parentsec gives the implementation the most freedom. It can
- 22:02Speaker 2: run jumps in parallel, and within each thread, it can
- 22:04Speaker 2: reorder or interleave operations on different elements. Often to take
- 22:08Speaker 2: advantage of SIMD instructions if the hardware supports.
- 22:10Speaker 1: It, so potentially the fastest, but maybe harder for the
- 22:14Speaker 1: programmer to reason about if side effects are involved.
- 22:16Speaker 2: Precisely, PARENTSEC demands more care regarding thread safety and lack
- 22:20Speaker 2: of dependencies between element operations. The book shows four each
- 22:24Speaker 2: with parentsec using an atomic counter, which is safe.
- 22:28Speaker 1: What about algorithms like std dot reduce or std dot
- 22:32Speaker 1: transform reduce, any special rules for parallelizing.
- 22:35Speaker 2: Them, Yes, a very important one. The operation you provide
- 22:38Speaker 2: addition for reduce or multiplication and addition for transform reduce
- 22:42Speaker 2: must be associative and commutative for the parallel versions to
- 22:46Speaker 2: guarantee the same result as the sequential one.
- 22:48Speaker 1: Associative and commutative like addition A plus B plus C
- 22:52Speaker 1: plus B plus c and A plus b egals b
- 22:54Speaker 1: plus a exactly.
- 22:56Speaker 2: If your operation doesn't have those properties, the result might
- 22:59Speaker 2: differ depending on how the parallel execution chunks and combines
- 23:03Speaker 2: the data. Floating point Edition strictly speaking, isn't associative, which
- 23:06Speaker 2: can sometimes cause tiny differences.
- 23:08Speaker 1: Good point. Are these policies just hints or guarantees of parallelism, They're.
- 23:13Speaker 2: More like permission slips or strong hints SDD dot execution.
- 23:17Speaker 2: DOT par allows parallel execution, but the library implementation might
- 23:22Speaker 2: decide to run it sequentially if it thinks that's faster. Eventually,
- 23:25Speaker 2: for very small ranges, it's not a strict guarantee of
- 23:28Speaker 2: end threads being used.
- 23:29Speaker 1: Does the book give any performance numbers? Is this speed
- 23:32Speaker 1: up real?
- 23:33Speaker 2: Yes, it shows a test case calculating tangents. The PAR
- 23:36Speaker 2: version on their quad core machine was significantly faster than SAKE,
- 23:40Speaker 2: close to a four x speed up. The parentsec version
- 23:43Speaker 2: was similar to PAR in that specific test, but your
- 23:45Speaker 2: mileage may vary absolutely. Performance depends heavily on the hardware,
- 23:49Speaker 2: the compiler, the specific algorithm, the data size, and the
- 23:52Speaker 2: operation being performed. Always benchmark your own code.
- 23:56Speaker 1: Sound advice. Okay, let's tackle a really modern feature. C
- 23:59Speaker 1: plus plus twenty quarantines. What's the fundamental difference from a
- 24:02Speaker 1: regular function.
- 24:03Speaker 2: The key idea is that they are resumable functions stackless, specifically.
- 24:07Speaker 1: Resumable, meaning they can pause and.
- 24:09Speaker 2: Continue later exactly. A regular function runs from start to
- 24:13Speaker 2: finish in one go. A core utine can execute a bit,
- 24:16Speaker 2: then cowight some operation or coiled of value, which suspends
- 24:20Speaker 2: its execution. Later, something can resume the core routine and
- 24:24Speaker 2: it picks up right where it left off, with all
- 24:27Speaker 2: its local variables intact.
- 24:29Speaker 1: So the state is saved somewhere, not just on the stack.
- 24:32Speaker 2: Right the state local variables suspension point is typically allocated
- 24:36Speaker 2: on the heap or in a quarutine frame managed by
- 24:39Speaker 2: the compiler, not just the traditional call stack. That's the
- 24:42Speaker 2: stackless part.
- 24:43Speaker 1: What makes a function become a core routine? Is there
- 24:45Speaker 1: a special keyword?
- 24:46Speaker 2: It becomes a quarantine if its body uses any of
- 24:49Speaker 2: the three Cortine keywords core return to return a value
- 24:52Speaker 2: and finish, suspend, co weight to suspend and wait for something,
- 24:57Speaker 2: or coiled to produce a value in a generator like sequence.
- 25:01Speaker 2: Even a range based for loop using co weight makes
- 25:04Speaker 2: it a core routine.
- 25:04Speaker 1: Okay, co return, cowight, coy yield. The book mentions handles,
- 25:08Speaker 1: suspend points, awaitables. Sounds like the machinery behind it it is.
- 25:12Speaker 2: Let's break it down quickly, go for it.
- 25:13Speaker 1: Quarantine handle that's.
- 25:15Speaker 2: Your remote control for the qure routine. An object you
- 25:17Speaker 2: can use to resume it, destroy its state, or check
- 25:20Speaker 2: if it's done.
- 25:21Speaker 1: Initial and final suspend points.
- 25:23Speaker 2: Every quarantine has a promise object associated with it. This
- 25:26Speaker 2: promise defines initial suspend and final suspend. These return special
- 25:31Speaker 2: awaitable objects like std dot suspenda ways or std dot
- 25:35Speaker 2: suspend never that control whether the quarantine suspends immediately when called,
- 25:39Speaker 2: and whether it suspends when it finishes via core return
- 25:42Speaker 2: or falling off the end.
- 25:43Speaker 1: So you can have a couroretine start suspended or run until.
- 25:45Speaker 2: The first CO eight exactly, and you can control if
- 25:48Speaker 2: it cleans itself up automatically when done, or waits to
- 25:51Speaker 2: be destroyed.
- 25:51Speaker 1: Via its handle and awaitables of waiters. That's for coit right.
- 25:55Speaker 2: When you cowight something that's something has to be an awaitable.
- 25:58Speaker 2: The compiler calls three key methods on the corresponding a
- 26:02Speaker 2: weight object, often the awaitable itself. A weight ready checks
- 26:07Speaker 2: if suspension is even needed. If not, it continues. If
- 26:10Speaker 2: suspension is needed, a weight suspend is called, which suspends
- 26:14Speaker 2: the quarantine and can schedule it for resumption later. When
- 26:17Speaker 2: it's time to resume, a weight resume is called and
- 26:20Speaker 2: its return value becomes the result of the cowight expression.
- 26:23Speaker 1: Okay, that's the core mechanism. The book had examples. One
- 26:26Speaker 1: preparing a job another using an event core routine.
- 26:29Speaker 2: Yeah, the job example was basic, showing the structure even
- 26:32Speaker 2: if it didn't suspend much initially. The event example was
- 26:35Speaker 2: more interesting for synchronization.
- 26:36Speaker 1: How did the event work.
- 26:38Speaker 2: It was a quarantine helper. You could cowight an event
- 26:41Speaker 2: object that courantine would suspend elsewhere code could call notify
- 26:45Speaker 2: on the event, which would resume the weighting core routine.
- 26:48Speaker 2: It's a way to build synchronization primitives using the quarantine
- 26:52Speaker 2: machinery itself.
- 26:53Speaker 1: Like a condition variable, but maybe fitting more naturally into
- 26:56Speaker 1: acen code flow.
- 26:57Speaker 2: Kind of. Yeah, it shows how coroutines can help manage
- 27:00Speaker 2: asynchronous waiting.
- 27:01Speaker 1: Let's look at the case studies. The book compared something
- 27:04Speaker 1: numbers in different ways. What was the fastest concurrent approach?
- 27:08Speaker 2: Right? They compared symbol, threaded, mutex protected, shared, some atomic shared,
- 27:13Speaker 2: some with different orderings, and finally a local sum approach.
- 27:17Speaker 2: Then the winner was by far the best concurrent performance
- 27:21Speaker 2: came from having each thread calculate a sum for its
- 27:24Speaker 2: own portion of the data into a local non shared variable.
- 27:28Speaker 2: Then only at the very end, each thread atomically adds
- 27:31Speaker 2: its local sum to the final shared result.
- 27:34Speaker 1: Variable, so minimize the shared operations do most work locally exactly.
- 27:38Speaker 2: Contention on the mutex or even the atomic variable in
- 27:41Speaker 2: the other approaches really killed performance locking or atomic ops
- 27:45Speaker 2: on every single edition was very slow compared to the
- 27:47Speaker 2: local accumulation.
- 27:49Speaker 1: Makes sense. The dining Philosopher's problem also came up. What
- 27:52Speaker 1: classic concurrency issues does that highlight?
- 27:54Speaker 2: Oh Dining Philosophers is the poster child for deadlock. It
- 27:58Speaker 2: perfectly illustrates how multiple actors philosophers competing for multiple shared
- 28:02Speaker 2: resources forks can easily get into a state where none
- 28:06Speaker 2: can proceed because they're all waiting for a resource held by.
- 28:09Speaker 1: Another the circular weight exactly.
- 28:12Speaker 2: The book uses it to show how flawed synchronization attempts
- 28:15Speaker 2: can lead to deadlock or maybe livelock, where they're busy
- 28:18Speaker 2: trying but making no progress, and it shows solutions like
- 28:22Speaker 2: establishing a strict ordering for acquiring the resources always pick
- 28:26Speaker 2: up the lower numbered fork first, for instance, to break
- 28:29Speaker 2: that circular dependency.
- 28:30Speaker 1: So resource ordering is a key deadlock prevention technique.
- 28:34Speaker 2: One of the most common and effective.
- 28:36Speaker 1: Ones singleton initialization again block based double checked locking, Meyer singleton,
- 28:41Speaker 1: what's the verdict?
- 28:42Speaker 2: Lock based is simple but potentially slow under contention double
- 28:46Speaker 2: check locking tries to optimize by checking first before locking,
- 28:50Speaker 2: but it's notoriously hard to get right and C plus
- 28:53Speaker 2: plus without hitting subtle memory ordering bugs. Avoid it unless
- 28:56Speaker 2: you really know what you're doing.
- 28:58Speaker 1: So Meyer's singleton datic local variable.
- 29:01Speaker 2: That's generally the way to go in modern C plus
- 29:03Speaker 2: plastatic tea instance return instance, since C plus plus eleven
- 29:07Speaker 2: the language guarantees this is thread safe and efficient, simple correct,
- 29:11Speaker 2: usually fast enough.
- 29:12Speaker 1: Good takeaway, Yeah, prefer meyer singleton CPMM was used again
- 29:17Speaker 1: to look at memory ordering and data races.
- 29:19Speaker 2: Yes, analyzing small examples, it visually reinforces how without proper
- 29:24Speaker 2: synchronization like mutexes or acquire release semantics, rights in one
- 29:29Speaker 2: thread are simply not guaranteed to be visible to reads
- 29:32Speaker 2: in another thread if they access the same non atomic
- 29:35Speaker 2: memory location. It makes the abstract memory ordering rules much
- 29:39Speaker 2: more concrete.
- 29:40Speaker 1: Seeing is believing, basically pretty much.
- 29:42Speaker 2: It helps you spot potential data races you might otherwise miss.
- 29:45Speaker 1: There was also a comparison condition variables versus atomic flags
- 29:49Speaker 1: for synchronization between two threads.
- 29:51Speaker 2: What was faster in the specific tests shown, which involved
- 29:54Speaker 2: repeated ping pong synchronization using atomic flags like std dot
- 29:58Speaker 2: atomic flag or std dot com atomic bool for the
- 30:01Speaker 2: signaling was found to be faster than using conditioned variables
- 30:04Speaker 2: in mutexes.
- 30:05Speaker 1: Why would that be It's likely due to overhead.
- 30:08Speaker 2: Atomic operations, especially on flags, can often be implemented very
- 30:12Speaker 2: efficiently by the processor, sometimes without involving the operating system kernel.
- 30:16Speaker 2: Conditioned variables in mutexes usually involves system calls for blocking
- 30:20Speaker 2: and waking threads, which adds more overhead.
- 30:24Speaker 1: So for simple signaling, atomics might be quicker, but condition
- 30:27Speaker 1: variables are more general.
- 30:28Speaker 2: That's a reasonable summary.
- 30:29Speaker 1: Yeah, and the last case study bit a coroutine returning
- 30:33Speaker 1: a future.
- 30:33Speaker 2: Yes, that just showed the nice integration. You can write
- 30:36Speaker 2: a function as a coroutine using coweight for internal ACYNC operations,
- 30:41Speaker 2: and then use coreturn to provide the final value. The
- 30:44Speaker 2: compiler automatically hooks this up, so the corotine returns an
- 30:47Speaker 2: std dot future or similar awaitable type that completes with
- 30:51Speaker 2: the core return.
- 30:51Speaker 1: To value, seamlessly bridging the two models exactly.
- 30:54Speaker 2: Let's use the corotine syntax internally while still interacting with
- 30:58Speaker 2: other code expecting futures.
- 31:00Speaker 1: Okay, let's gaze into the crystal ball see plus plus
- 31:02Speaker 1: twenty three and beyond. Executors are presented as a big deal.
- 31:06Speaker 1: What's the core concept?
- 31:07Speaker 2: Executors are intended to be a fundamental abstraction for how, where,
- 31:11Speaker 2: and when work gets done. They define the execution context.
- 31:15Speaker 1: Execution context like which threadpool or run on the GPU or.
- 31:21Speaker 2: Inline potentially all of the above. The idea is to
- 31:24Speaker 2: separate what the function or task you want to run
- 31:27Speaker 2: from the how or when, which is defined by the executor.
- 31:30Speaker 2: You'd submit your task to an executor, and the executor
- 31:32Speaker 2: decides how to run it.
- 31:33Speaker 1: So it's a unified way to handle thread pools, inline execution,
- 31:37Speaker 1: maybe event loops.
- 31:38Speaker 2: That's the goal, a standard, composable way to represent and
- 31:42Speaker 2: manage different execution strategies. The book sees them as foundational
- 31:46Speaker 2: for future concurrency libraries, networking, etc.
- 31:49Speaker 1: What kind of properties can these executors have?
- 31:51Speaker 2: The proposals discuss properties like directionality, is it fire and
- 31:55Speaker 2: forget one way? Does it return a future two way?
- 31:58Speaker 2: Does it support continuations then then cardinality? Does it run
- 32:01Speaker 2: one task, single or many? Bulk blocking behavior? Does submitting
- 32:05Speaker 2: work potentially block the caller? Possibly always never?
- 32:09Speaker 1: And you could potentially query or acquire executors with certain properties.
- 32:12Speaker 2: That's the idea, using mechanisms like execution dot require or
- 32:17Speaker 2: prefer to tailor the execution context to your needs.
- 32:20Speaker 1: How might this integrate with things like std dot ASNC
- 32:23Speaker 1: or parallel algorithms.
- 32:25Speaker 2: The vision is you'd be able to pass an executor
- 32:27Speaker 2: object to std dot ASNC or to the parallel algorithms
- 32:30Speaker 2: to control where and how they run, instead of them
- 32:33Speaker 2: always using some default mechanism like a hidden global threadpool.
- 32:37Speaker 2: More control, more flexibility.
- 32:38Speaker 1: What are the main design goals for executors?
- 32:41Speaker 2: Usability both for library writers building on them and for
- 32:45Speaker 2: application developers using them, composabilities so you can layer and
- 32:48Speaker 2: combine executors, and minimality, keeping the core concepts lean and extensible.
- 32:53Speaker 1: You mentioned single versus bulk cardinality. What's the difference in
- 32:56Speaker 1: how they execute?
- 32:57Speaker 2: Single cardinality functions one way execute, two U way execute
- 33:00Speaker 2: then execute, take one callable and run at once. Bulk
- 33:03Speaker 2: functions take a callable and a shape like account and
- 33:06Speaker 2: run the callable multiple times, possibly in parallel, passing an
- 33:09Speaker 2: index or other info to each invocation. Useful for parallel
- 33:12Speaker 2: for style operations.
- 33:14Speaker 1: Got it? The book mentioned some ongoing concerns like when
- 33:18Speaker 1: all wenny return types and blocking future destructors.
- 33:21Speaker 2: Yeah, those are known complexities. Combining futures with when all
- 33:24Speaker 2: weny can lead to complicated return types, and the fact
- 33:28Speaker 2: that std dot ASNC can return a future that blocks
- 33:31Speaker 2: in its destructor if you don't get the result is
- 33:34Speaker 2: problematic as it can accidentally serialize your code. There are
- 33:38Speaker 2: active proposals trying to refine these areas.
- 33:41Speaker 1: What about synchronized in atomic blocks in C plus plus
- 33:44Speaker 1: twenty three sound related but different.
- 33:47Speaker 2: They are both aim for atomic execution of a code block.
- 33:50Speaker 2: Synchronized blocks are more relaxed. They act like the block
- 33:53Speaker 2: is guarded by a single global mutex, providing a total order.
- 33:56Speaker 2: They can contain things like io atomic blocks at no
- 34:00Speaker 2: accept atomic commit, atomic cancel are for true transactions. They
- 34:03Speaker 2: have stricter rules about what they can contain no non transactions,
- 34:07Speaker 2: safe operations, and explicit handling of exceptions commit or cancel
- 34:10Speaker 2: the transaction.
- 34:11Speaker 1: So atomic blocks are closer to database transactions.
- 34:14Speaker 2: Conceptually, yes, aiming for that kind of atomicity, though without
- 34:17Speaker 2: the durability aspect.
- 34:19Speaker 1: Usually and taskblocks a fork joint model.
- 34:21Speaker 2: Right. Taskblocks provide structured parallelism. You define a work launch
- 34:26Speaker 2: subtasks within it. The fork the thread that started the block,
- 34:29Speaker 2: automatically waits at the end of the block until all
- 34:31Speaker 2: launch subtasks are complete. The join makes managing parallel task
- 34:35Speaker 2: dependencies much simpler.
- 34:37Speaker 1: Okay, And lastly, for C plus plus twenty three, the
- 34:40Speaker 1: Data Parallel Vector Library SAMD.
- 34:44Speaker 2: This aims to standardize SIMD programming in C plus plus,
- 34:48Speaker 2: providing standard vector types that map to hardware SIMD registers
- 34:51Speaker 2: and operations on them. Features like masked operations apply an
- 34:55Speaker 2: operation only where a condition is true, and traits to
- 34:58Speaker 2: query vector properties like size are part of it, making
- 35:01Speaker 2: SIDY more portable and accessible.
- 35:03Speaker 1: Lots of interesting stuff potentially coming. Let's switch to synchronization patterns,
- 35:06Speaker 1: architectural design idioms. What's the difference?
- 35:09Speaker 2: Think levels of abstraction. Architectural patterns like reactor proactor define
- 35:14Speaker 2: the high level structure of a concurrent system. Design patterns
- 35:17Speaker 2: like active object monitor describe common interaction solutions between components.
- 35:22Speaker 2: Idioms are lower level se plus specific techniques like scope locking.
- 35:26Speaker 1: And using patterns helps out.
- 35:27Speaker 2: Gives you a shared vocabulary, makes designs clearer, lets you
- 35:31Speaker 2: reuse proven solutions instead of reinventing the wheel. They build
- 35:35Speaker 2: on best practices but are more specific named solutions to
- 35:39Speaker 2: recurring problems.
- 35:41Speaker 1: What patterns help with managing shared data?
- 35:43Speaker 2: The book mentions things like copying the value avoids sharing
- 35:48Speaker 2: mutable state altogether good for value types, thread specific storage.
- 35:52Speaker 2: Each thread gets its own copy using futures, share the
- 35:56Speaker 2: result once it's ready.
- 35:57Speaker 1: And patterns for handling mutations safely one include scoped locking
- 36:02Speaker 1: using std dot lockered or std.
- 36:04Speaker 2: Dot unique lock for RAI mutex management, strategize locking using
- 36:08Speaker 2: templates or polymorphism to vary the locking strategy, thread safe
- 36:11Speaker 2: interface designing the class itself to handle internal synchronization, guarded
- 36:16Speaker 2: suspension using condition variables to wait for preconditions, and always.
- 36:19Speaker 2: The book warns about lifetimes when passing references to threads.
- 36:22Speaker 1: Right the architectural patterns active object, monitor, half sync, have
- 36:26Speaker 1: async reactor proactor.
- 36:28Speaker 3: Can we get a super quick idea of each okay
- 36:30Speaker 3: quick fire active object decouple's method call from execution uses
- 36:35Speaker 3: an internal thread and message que monitor object synchronizes access
- 36:39Speaker 3: to an object's methods, usually one lock for the whole object.
- 36:43Speaker 2: Half sync half ACYNC separates asinc tasks verr gio in
- 36:47Speaker 2: a thread pool from sync processing. You examle main logic thread,
- 36:51Speaker 2: often using a queue reactor, single thread, weights for events,
- 36:56Speaker 2: synchronously dispatches to handlers. Proactor waits for completion of ace
- 37:00Speaker 2: zinc operations, then calls handlers leverages acinc os features.
- 37:04Speaker 1: Got it. The book uses boost assio for a reactor example.
- 37:06Speaker 2: Yes, showing how that library implements the event loop and
- 37:09Speaker 2: handler dispatch typical of the reactor pattern.
- 37:11Speaker 1: Moving on to best practices, what are the absolute top.
- 37:14Speaker 2: Ones number one, far and away. Minimize shared mutable state
- 37:17Speaker 2: If data isn't shared or isn't mutable, concurrency gets vastly simpler.
- 37:21Speaker 1: Avoid the problem if you can.
- 37:23Speaker 2: Exactly if you must have shared mutable state. Ensure proper
- 37:26Speaker 2: synchronization mutext as atomics, et cetera. Minimize waiting time. Amdell's
- 37:31Speaker 2: law limits speed up based on sequential parts. Use a
- 37:34Speaker 2: mutability const expert where possible. Use RAII for locks lockguard.
- 37:40Speaker 2: Don't use condition variables without predicates. Prefer higher level tools
- 37:44Speaker 2: a std dot acinc. Parallel algorithms over raw threads when appropriate,
- 37:48Speaker 2: and understand the memory model.
- 37:50Speaker 1: Understand the memory model. It seems full circle on that one. Okay,
- 37:54Speaker 1: Concurrent data structures, stacks, ques, What are the challenges?
- 37:59Speaker 2: The main chate is maintaining the data structure's internal consistency.
- 38:03Speaker 2: It's invariance when multiple threads are operating on it simultaneously.
- 38:07Speaker 2: A simple example is a stack. What if one thread
- 38:09Speaker 2: tries to pop while another is reading the top. You
- 38:11Speaker 2: might get inconsistent results or errors.
- 38:13Speaker 1: How do you fix that? Locks?
- 38:15Speaker 2: Locks are the first step. Coarse grained locking one big
- 38:18Speaker 2: lock for the whole structure is simpler, but limits concurrency.
- 38:21Speaker 2: Fine grained locking multiple locks for different parts allows more parallelism,
- 38:25Speaker 2: but is much harder to get right.
- 38:27Speaker 1: The book mentioned changing the interface sometimes.
- 38:29Speaker 2: Yes like instead of separate top on pop on a stack,
- 38:33Speaker 2: provide a single atomic top app operation. This avoids the
- 38:37Speaker 2: race condition between checking the top and removing it.
- 38:40Speaker 1: What about lock free structures?
- 38:41Speaker 2: That's the next level, avoiding locks entirely using a comic
- 38:45Speaker 2: operations like compare and swap. This can offer better performance
- 38:49Speaker 2: and avoids deadlock, but it's extremely complex. You run into
- 38:53Speaker 2: issues like the ABA problem, and memory reclamation becomes very tricky.
- 38:57Speaker 2: The book mentions hazard pointers as one solution a problem
- 39:01Speaker 2: where a location reads value a then computation happens then
- 39:04Speaker 2: it reads A again, but in the meantime another thread
- 39:07Speaker 2: changed it to B and then back to A. Your
- 39:10Speaker 2: comparent swap might succeed, thinking nothing changed, but the underlying
- 39:14Speaker 2: state is different. Needs careful handling.
- 39:17Speaker 1: Wow, concurrent data structures sound like a deep topic on their.
- 39:20Speaker 2: Own, they really are. The book gives a taste, including
- 39:22Speaker 2: a lock free stack using C plus plus twenty atomic
- 39:25Speaker 2: smart pointers.
- 39:26Speaker 1: What about the time library chrono? How did that relate?
- 39:29Speaker 2: Krono is essential for measuring performance, setting timeouts, managing timed weights.
- 39:34Speaker 2: It provides clocks system clock for wall time, steady clock
- 39:38Speaker 2: for intervals, time points, specific moments and durations, intervals, very
- 39:42Speaker 2: flexible for representing time.
- 39:44Speaker 1: Accurately, and atomic operations, transactional memory any final points there.
- 39:50Speaker 2: The book mentions atomics should ideally be addressed free atomic
- 39:53Speaker 2: even across processes sharing memory, and it touches on ACD
- 39:57Speaker 2: properties atomicity, consistency, isolation, durability for transactions, noting that C
- 40:03Speaker 2: plus plus transactional memory proposals focus mainly on AC and I,
- 40:07Speaker 2: with durability being less of a focus than in databases.
- 40:10Speaker 1: And finally, a glossary that sounds useful.
- 40:13Speaker 2: Very concurrency has a lot of specific terminology, acquire, release, data, RaSE, deadlock,
- 40:17Speaker 2: sequential consistency, et cetera. The glossary helps nail down those definitions.
- 40:21Speaker 1: Wow, Okay, we have definitely covered a lot of ground
- 40:23Speaker 1: there based on the material. Real deep dive into modern
- 40:26Speaker 1: C plus plus.
- 40:27Speaker 2: Concurrency absolutely from the memory models, tricky foundations, rite up
- 40:31Speaker 2: to currotines, parallel algorithms, and a peak at what's coming
- 40:35Speaker 2: with executors. C plus plus provides a pretty powerful set
- 40:39Speaker 2: of tools.
- 40:39Speaker 1: So for you lifting in, I think the big takeaway
- 40:43Speaker 1: is that concurrency really forces a shift in thinking compared
- 40:46Speaker 1: to sequential code, timing, interaction, ordering. It all becomes critical, right.
- 40:52Speaker 2: It unlocks performance potential, but also opens up whole new
- 40:55Speaker 2: categories of bugs like data races and deadlocks if you're
- 40:58Speaker 2: not careful.
- 41:00Speaker 1: Vigilance is needed, and this is an evolving field, right.
- 41:03Speaker 2: Definitely, the C plus plus standard keeps adding features, best
- 41:06Speaker 2: practices emerge, So we'd encourage you to maybe pick an
- 41:09Speaker 2: area that caught your interest today and dig deeper. Try
- 41:12Speaker 2: out the parallel algorithms, maybe write a small program using
- 41:15Speaker 2: j thread. When C plus plus twenty three features become available,
- 41:19Speaker 2: experiment with executors.
- 41:21Speaker 1: Or Even if you're feeling brave, try implementing a simple
- 41:23Speaker 1: lock free structure just to appreciate the complexity exactly.
- 41:27Speaker 2: The more you work with it, the better your intuition becomes.
- 41:30Speaker 1: Ultimately, understanding of these concepts put you in a much
- 41:33Speaker 1: stronger position to build modern software. Being able to reason
- 41:36Speaker 1: about concurrency is just It's becoming a non negotiable skill
- 41:41Speaker 1: in our multi core world.
- 41:42Speaker 2: Couldn't agree more.
- 41:44Speaker 1: Thanks for joining us on this deep dive.