I’m filing this one under teaching diary category.
Today I asked one of my student-geeks to explain to me what a mutex is. 45 minutes later, he left my office, I have a headache, and I understand what a mutex does. He’s 15 years old.
I love my job.
edit later in the evening, this student sent me the following email:
Wow I just realized I did an awful job of explaining mutexes, but instead actually gave u the model i prefer, which is essentially designed to avoid them. whoops. Anyway, the mutex itself is the lock (or rather what a lock is called in unix systems—MUTualExclusion (lock)). Basically think of it as an atomic pthread * (way to impl. specific, sorry) where when you need a resource associated with a lock, you do some system call (or something) to make the mutex point to the current thread (which is *acquiring* the lock) as long as it is null. If it is not null, it has been acquired by a different thread, and you need to not use whatevers associated with that lock until it is released by whatever other thread is using it—which would set it to null. some common actions would be to implement a ‘spin’ lock, which basically is
or canceling the action. Note that resources associated with a lock are entirely programmer defined, meaning that you can do whatever you want with them, and you wont be stopped even if you dont have a lock, but the idea is to acquire the lock before using the resource (this is obvi way simple in object oriented code, where accessors can just acquire a lock thats an ivar of the object before actually changing the ivar). Many things which are ‘thread safe’ actually just use mutexes internally on all state variables. Second note - the impl. i described is prbly not at all the way unix does it, and syscalls are probably not involved—gcc has builtin atomic operations which just show that this doesn’t need to involve semaphores, although it sometimes does (beyond this is farther than I have plunged into OS kernel level stuff), but basically the main things to know are that with a mutex you acquire and release it. Oh, and mutexes make poor performance code, being that you’re literally just intentionally wasting cycles waiting for something while you spin.
I think thats it
(I _really_ love my job)
Published on Monday, April 26, 2010 (8 years, 11 months, and 3 weeks ago). Posted in: Teaching Diary