I make an application in which a model is constantly being processed and a little less often is drawing it. At first I did the calculations in NSTimer , everything worked as it should, but the timer consumes too much energy and is not created for such a task at all. Therefore, I decided to remake a separate stream.
From the processing flow, information arrives at the output only through a class variable named roof of the type CGContextRef - in the main flow this thing is regularly drawn. Obviously, without additional manipulation, sooner or later two threads will try to access this variable at the same time, it is necessary to synchronize.
For this, I tried to use both NSLock and the mutex of the classic pthread (is it compatible with NSThread ?), But to no purpose, with the time this error still takes off. @synchronized is not appropriate, since it accepts only objects of some class.
I create the stream in the standard way:
[NSThread detachNewThreadSelector:@selector(thread) toTarget:self withObject:nil]; NSLock used this:
// Interface: NSLock *locker; // In awakeFromNib: locker = [NSLock new]; // Everywhere I use roof: if ([locker tryLock]) { // ...using of the roof... [locker unlock]; } And pthread like this:
// Interface: pthread_mutex_t mutex; // In awakeFromNib: pthread_mutexattr_t attributes; pthread_mutexattr_init(&attributes); pthread_mutexattr_settype(&attributes, PTHREAD_MUTEX_NORMAL); pthread_mutex_init(&mutex, &attributes); // Everywhere I use roof: pthread_mutex_lock(&mutex); // ...using of the roof... pthread_mutex_unlock(&mutex); What did I code wrong?