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?

  • End the alarm; I was mistaken that I didn’t set synchronization in all places. Corrected, checked: both ways work as it should. In general, always check the detour using common variables. I'll leave the question, maybe these two blanks of mutex will be useful to someone. - AivanF.
  • Well, then delete - Max Mikheyenko
  • @MaxMikheyenko help to share knowledge. On ruSO, I did not find any records about mutex on ObjC, so let it be better to stay. I think the moderators will agree with me. - AivanF.
  • then post your answer - Max Mikheyenko

1 answer 1

End the alarm; I was mistaken that I didn’t set synchronization in all places. Corrected, checked: mthex from pthread works as correctly as NSLock .
In general, always check the detour using common variables. I'll leave the question, maybe these two blanks of mutex will be useful to someone.

And if that, useful links on the topic:
About synchronization options and NSLock on Apple Developer,
About pthreads on Habrahabr.