开发者

What happens when a thread attempts to access a mutex-locked resource?

开发者 https://www.devze.com 2023-03-28 01:23 出处:网络
I\'m currently creating an SDL/OpenGL program, which renders objects based on a few state variables.These state variables are updated continuously in a seperate thread, at a user-defined rate.Every on

I'm currently creating an SDL/OpenGL program, which renders objects based on a few state variables. These state variables are updated continuously in a seperate thread, at a user-defined rate. Every once in a while, the main thread asynchronously needs to swap some of these state variables.

Now, these state variables are mostly pointers, so when I update them from the main thread (i.e. asynchronously with respect to the updating thr开发者_JAVA百科ead), I first create a mutex lock, delete the objects, create/swap them to their new ones, and then unlock the mutex. Again though, the update thread is still running during this time.

Because of that last point, I was curious. What happens if the thread attempts to access any of those state variables mid-asynchronous-update? I know that this isn't allowed (due to the mutex lock), but what happens behind-the-scenes?


Unless you cover your update code with mutex lock and unlock, the update thread(your last point) won't care about the lock by main thread. It will just update that data.

You should use the same mutex object(just create it ones for the lifetime of update thread and main thread) on the update thread before updating the variables. This way, main thread won't get access to that data while update thread is accessing and vice versa.

You may want to take a good look at how mutex's are used for synchronization of threads.

UPDATE: FOR YOUR QUESTION

"So basically, everywhere I have a thread-unsafe variable, I should surround all accesses to that variable with the same mutex?"

Yes, but you should also be aware of scenarios where deadlock can occur. deadlocks are main reason why multi threading is avoided in many applications or to put it in another way, many people don't like multi threading.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号