CST 334 - Operating Systems (Week 6)
This week, while working on my final programming assignment about threads, I learned something very interesting. The first thing is using thread in programming language is simple, much more than when I had to dealt with iterator or pointer. Now, that doesn't mean the whole concept of thread and multi-threading are simple as well. In fact, under the hood, they are extremely complicated and there are many aspects that we need to account for, such as lock, race condition or indeterminate. However, on the surface, thread is still straight forward, to the point that I didn't believe in my eyes and my mind. I should thank my instructor for crafting a solid assignment to make students' life less misery.
The next thing I learn is... more fascinating in my opinion. While working on the second half of the programming assignment, I stumbled into the concept of joining concept. Whenever we create and run a sub-thread (beside the main thread), we have to join the thread in the end. Now, let's me explain the general concept first. When the thread is done with its tasks, thread is finished but it still remains around. We have to join completed thread to the main thread, which signal the operating system to clean up the resources that the thread used. Without doing the join, thread may occupy the resources and pile up, resulting in resource leak later on.
Now that's not the only interesting knowledge I discovered. When joining thread, we have two ways: join( ) and detach( ). For detach, it has similar concept except that the thread join itself immediately after it finishes with given tasks. It sounds extremely convenient indeed, but there are scenarios that we have to join threads ourselves. For example, we create a thread to read some data multiple times. If we use detach() for convenient purpose, there is a chance that the thread closes itself before we finish processing the data. In that case, we know when we need to join the thread, and join( ) is definitely the better choice. Therefore, we must understand what we need to do with threads and decide whether we join ourselves or automatically.
One additional note about joining thread is the rule for not letting the thread run for a long time. Why? You may think it is best to have sub-threads run and handle given tasks from time to time, rather than join and recreate again. Moreover, you may choose to do so because you don't know when it is best to join the thread. However, do not forget that sub-threads how the resources that only get cleaned up when we join. And if we let sub-threads run on background like that, we risk running out of resources. In conclusion, specify the task for thread and when it is done. Then we will know whether we can close it automatically or whenever we can close it ourselves.
.png)
Comments
Post a Comment