|
|
| Perl-Sensitive Sunglasses | |
| PerlMonks |
Re^2: Do I need threads?by Marshall (Canon) |
| on Dec 22, 2011 at 00:55 UTC ( [id://944715]=note: print w/replies, xml ) | Need Help?? |
|
You are almost there. This code will work most of the time. But that is not "all of the time". The issue is how you handle multiple children writing to the log file. A context switch can happen at any time including during the middle of a child doing a write to the log file! The result is that occasionally you will get garbled data in the log file.. maybe child 1 starts writing a line...then child 2 starts running and writes its stuff right in the middle of the line from child 1, then child 1 runs again to finish its line. Result garbled stuff. To fix this, the children have to cooperate so that only one at a any one time is writing to the file. You can just have the children acquire an exclusive file lock, do the write, then release the lock. A blocking wait for the exclusive lock is ok here - you don't need to fiddle with a shared reading lock. See: file locking for more details on how to do it. Also there is another way to wait for the children, wait(). What you have is fine, but you can just wait() (blocking) for all of the children to finish. That way you wouldn't have to keep track of the pid's of the children. The OS knows who your children are. Anyway, the main functional issue is using flock() to coordinate the children. Your writes are quick and there isn't that many of them so it might be awhile before you see the problem, but it will eventually happen.
In Section
Seekers of Perl Wisdom
|
|
||||||||||||||||||||||||||||||||||||