1

If we need to implement a queue (being done by NSMutableArray), and we have Producer objects that add data to the queue. There can be 1 producer or multiple producers. And if the queue is full (at size of 100, for example), the thread should be "blocked" (waiting, until the queue is actually smaller size than 100 items). (the same goes for taking away data from the queue: when it is empty, the getting of data is also blocked).

How can this "blocking" be implemented? Right now I use a Mutex

@property (strong, atomic) NSLock *lock;

so that the count of the NSMutableArray is obtained and adding of item is done together (because the count can be 99, but when the item is added, the count can already be different).

But for the blocking effect, I actually check the count, and if 100, release the lock and sleep for 0.1 second, and then get the lock again and get the count, and repeat as above.

Is this a good way to implement the "blocking" behavior? There seems to be another way to get a canAddNowLock, which is simply blocking by the NSLock mechanism, and when a queue item is removed, then release this canAddNowLock, but since there can be multiple data producers and data consumers, what if several producers are unblocked, or what if multiple consumers unlock canAddNowLock in a row and only 1 producer is unblocked (when in fact several producers should be unblocked)? It just seem a more complicated design that way.

4

1 回答 1

1

使用 NSCondition *条件线程1:

[condition lock];
//check the queue is not full
[condition wait];//if already full, wait
//check again
//put something into queue
[condition unlock];

线程2:

[condition lock];
//check the queue is not empty
//get something from queue
[condition signal];
[condition unlock];
于 2012-08-24T01:36:50.517 回答