Hi!
Mission: Collect data from various sources and write to xml-file as soon as the data is available using multithreading.
Code:
use XML::Writer;
use IO::File;
use threads;
use strict;
my $output = new IO::File(">output.xml");
my $writer = new XML::Writer(OUTPUT => $output, DATA_MODE=>1, DATA_IND
+ENT=>1,CHECK_PRINT=>1);
$writer->xmlDecl("UTF-8");
$writer->startTag('operations');
my $thr1 = threads->new(\&writeArticleData1);
my $thr2 = threads->new(\&writeArticleData2);
while (!(($thr1->join) && ($thr2->join)))
{
# Wait for threads to finish
}
$writer->endTag("operations");
$writer->end();
$output->close();
sub writeArticleData1()
{
lock($writer);
$writer->startTag('product');
$writer->characters("Hello, world!");
$writer->endTag("product");
sleep 2;
return 1;
}
sub writeArticleData2()
{
lock($writer);
$writer->startTag('product');
$writer->characters("Hello, world2!");
$writer->endTag("product");
return 1;
}
1;
Output:
<?xml version="1.0" encoding="UTF-8"?>
<operations>
<product>Hello, world2!</product>
<product>Hello, world!</product></operations>
I'm very close to reach my goal as you can see, but for some reason, the closing tag for operations doesn't get it's own row as supposed. Which makes me questioning my way of doing it. So, questions:
1. Am I using threads in the right way?
2. Am I thinking correct regarding the "lock" usage?
3. Do you see any other pitfalls regarding scoping and such?
4. Can I fix the particular problem?
The resulting document _doesn't_ need to be formatted as such, I'm just questioning my own ways of using threading in this case. Maybe XML::Writer doesn't support it? Or maybe a filehandle issue?
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.