If multiple threads print to a filehandle at the same time, their output can become interleaved. Ie. bits of one line get mixed into another line. Like two people talking at the same time.
The shared variable: $semSTDOUT simply acts as a semaphore to prevent this. By locking that variable before printing, it ensures that each line of print is output whole.
If you've read "Lord of the Flies", the variable is acting like the conche shell.
It returns the thread id of the "current" thread.
The reason it always returns 0 in the example, is because tprint() is only ever called from thread 0--the main thread. But if you add some trace to the other threads, each threads output will be prefixed by its thread id which is useful for debugging.
Yes. Thread::Queue takes care of all the required locking. Each $Q->dequeue() will return the next value from the queue. Once read, it is removed and no other thread will ever know it was ever there.
If the work Q feeding code was not in a separate thread from the results Q reading code, then you would not start to see the results until all the work items had been queued and processed.
You could feed the queue in a single burst, but if the list is large, that would consume a large amount of memory. Better to keep the queue size small by feeding just enough to keep the workers busy.
You could try to multiplex the feeding of the work Q and the reading of the results Q. But that just gets messy and creates potential for deadlocks.
Rather than trying to do two different things a the same time in one thread--with all the synchronisation problems that creates--better to start another thread and let each thread concentrate on doing one thing simply.
That's the purpose of threading.
Thanks, this seems to be a good shell for what I need to do (though I'll probably wear out the Perl book figuring it out).
NP. If you have any further questions, do ask them. It is far easier to answer your questions, than to try and predict every question you might ask, and clutter the code with long rambling comments attempting to answer them.
In reply to Re^9: Win32::Process output
by BrowserUk
in thread Win32::Process output
by tawnos
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |