homework5 Version 0 |
|
👤 Author: by 1403861656qqcom 2020-10-31 02:13:06 |
- (void)buyFunction {
// Keep buying tickets if there are more than one
while (sum > 0) {
// Print the current ticket number before purchase
NSLog(@" thread %@ ready to buy tickets :%d tickets ", [NSThread currentThread].name, sum);
// Simulate purchase operation, vote -1
sum--;
}
// Print the current number of tickets when they are sold out
NSLog(@" thread %@: tickets sold out :%d tickets left ", [NSThread currentThread].name, sum);
}
Now we open two threads to perform this operation at the same time, starting with 10 tickets (sum = 10), check the console output:
Thread 2 ready to buy tickets :10 tickets left
Thread 1 ready to buy tickets :10 tickets left
Thread 1 ready to buy tickets :9 tickets left
Thread 2 ready to buy tickets :8 tickets left
Thread 1 ready to buy tickets :7 tickets left
Thread 2 ready to buy tickets :6 tickets left
Thread 1 ready to buy tickets :5 tickets left
Thread 2 ready to buy tickets :4 tickets left
Thread 1 ready to buy tickets :3 tickets left
Thread 2 ready to buy tickets :2 tickets left
Thread 1 ready to buy ticket remaining :1 ticket
Thread 2: Tickets sold out Remaining :0 tickets
Thread 1: Tickets sold out Remaining :-1 ticket
As a result of our observations, we found some problems:
(1) The remaining tickets are the same in the two ticket buying processes
I bought the same ticket twice
(3) I was bought once after I had no tickets left
Solution:Process/thread synchronization is a major problem in data sharing of operating systems. It requires not only hardware and system-level implementation, but also programmers to avoid deadlocks during development. Synchronization is inseparable from deadlocks