• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: How to use NSLock
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: How to use NSLock


  • Subject: Re: How to use NSLock
  • From: Brendan Younger <email@hidden>
  • Date: Sun, 02 Jan 2005 10:39:00 -0600


On Jan 2, 2005, at 3:22 AM, Peter Karlsson wrote:

Dear list!

Can some please explain how I use NSLock to protect a variable from being
used or destroyed by another thread?


My app have 2 threads and a readProc. The normal thread that is always
there and a second thread that starts when I want to request a sysex dump
from my synthesizer.


The variable 'sysexcounter' is used in 2 places.

1 - 'sysexcounter' is incremented In my readProc that get the MIDI bytes

2 - In my second thread my app waits for 'sysexcounter' to get a predefined
value that is the size of my sysex message before the code flow continues.


But it seems that something happens that makes 'sysexcounter' useless. So I
want to protect it from being used by 2 places at the same time. I think
that is the right way to explain my problem.

Clark Cox's solution will work, but if I understand you correctly, you are implementing producer/consumer threads and so you really want to sleep one thread while waiting for a sysex message. In this case, you should use NSConditionLock. The code should look something like this:


enum {
	kEmpty,
	kFull
};

// Thread 1
while(1) {
...get more data here
[lock lock];
status = (sysexcounter == sizeof_sysex_message) ? kFull : kEmpty;
[lock unlockWithCondition:status];
}

// Thread 2
while(1) {
	[lock lockWhenCondition:kFull];

	...process sysex message here

	[lock unlockWithCondition:kEmpty];
}

Though I should point out that simply protecting sysexcounter is not sufficient if I understand your needs correctly. You also need to protect whatever buffer you're reading/writing into as well. In that case, it's probably easier to make a queue out of an NSMutableArray and a NSConditionLock which just contains NSData's from the MIDI thread. Then you know that all the data is only owned by one thread at a time.

Brendan Younger

_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list      (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden


References: 
 >How to use NSLock (From: "Peter Karlsson" <email@hidden>)

  • Prev by Date: nsbutton
  • Next by Date: Re: Calling AppleScript from Cocoa
  • Previous by thread: Re: How to use NSLock
  • Next by thread: RE: Re: How to use NSLock
  • Index(es):
    • Date
    • Thread