homework-4 Version 0 |
|
👤 Author: by 781863542qqcom 2019-10-09 11:08:17 |
Think about your possible case about process synchronization, and give out a solution for the problem.
Answer:For example, when the spring festival is drawing near, people will visit transportation agency websites like www.12306.cn and buy tickets to get home.When they query the remaining tickets, the server performs a database query and return the result to users. When they buy and pay for the tickets, the server select the corresponding database records and change the value.Things are simple when there is only one user.However, the fact is that people from every where visit the websites and the websites' traffic is huge.The websites should be able to make full use of spare time to respond to users' request while waiting for some costly work to be done(like IO and database query).It is the situation where multi-threading can help.But the problems multi-threading brings are the synchronization between threads, to name but a few, when there is only one ticket left and two users buy it at the same time, the computer must select a request and refuse another, if the computer simply substract the remaining ticket number, the result will be -1 and it's obviously wrong.To address these problems, we need rely on some tools, the most used are mutex, semaphore, conditional variable and in this situation mutex is the best.Mutex is like a lock and the lock/unlock operation are guaranteed to be atomic. When a operation needs to modify the database, it should at first acquire the ownership of the mutex, if not, it must wait for another thread release the mutex. Once the thread has finished work, it release the mutex and another waiting thread will acquire the mutex.For those operations that only read database, thread synchronization are not required.