file race condition?

It’s about Mail.app and rule action script again. I seem to observe a file race condition: in my AppleScript script I have it write to a set of files, waiting for some shell script to pick up. Normally it won’t be a problem. But when multiple messages are going through the rule, I guess it’s possible that the AppleScript script starts writing to the same file while the shell script hasn’t been able to finsh its business?

Here is the file writing snippet in AppleScript:

set subjectF to (open for access file “Macintosh HD:private:tmp:jmSubject.txt” with write permission)
set eof subjectF to 0 --empty anything previously in the file
write theSubject as string to subjectF
close access subjectF

If it is an external shell script (not hardcoded within your script), most probably it will overlap the execution. However, if you include the “do shell script” statement in your script, there is no problem, since it will wait while its execution is not finished.

Thanks for the reply. Please see this thread

http://bbs.applescript.net/viewtopic.php?t=5805

the script I’m referring to is that junk filtering script, attached to Mail.app via rule action. So I guess if Mail.app executes rule actions in parallel, I might run into file race problem?

Yah! There are possibilities of file race. I used this code:

global counter

on perform_mail_action(info)
	set counter to 0
	tell application "Mail"
		set theMessages to |SelectedMessages| of info
		repeat with i in theMessages
			set counter to counter + 1
		end repeat
	end tell
	display dialog counter
end perform_mail_action

I used 100 messages for my test and seems that Mail executes groups of “x” messages (6, 4, 3, 5…). I don’t know if it does create every time a new instance of the script (most probably if you noted it). If it does, it is possible that you get several instances of the same code writing to the same file.
Perhaps you can create unique names for your files, so they aren’t overlapped, some kind of algorithm, such as length of body + uptime + “.txt”. :?:

I used the message ID to form the filenames, so as long as there’re no duplicate message IDs I guess I’m safe? But your suggestion of using system time as part of the filename is excellent, unless the resolution is not fine enough… do you know the right command to use in AppleScript? (sorry I’m still a newbie to AppleScript) Thx!

Message id is the coolest solution. At least in Entourage, each new message receives a new numerical ID, so there are not duplicated ids.
You can get the uptime, currently, in AS, in ticks (1/60 seconds) and milliseconds, but you need third-party scripting additions:

the ticks --> jon's commands
GetMilliSec --> GetMilliSec.osax

You can get latest Jon’s Commands at http://www.seanet.com/~jonpugh/
And GetMilliSec here: http://osaxen.com/getmillisec.html