views:

62

answers:

2

I will listen on a port (simple server) when a request is passed parse the URL and start a thread.

The thread will insert an element in a queue which is shared, and it is locked while inserting.

I am not able to get element when I call peek on queue.

use Thread qw(async); 
use Thread::Queue;

 my $DataQueue:shared = new Thread::Queue; 

 $newElement = init($user,$param,$reqest);  # init is method in ElementStructure.pm
 #after creating the element it is passes to subroutine where thread is started

sub updateData
{
    my $iElement=shift;

    $thr = async 
    { 

        {
            lock($DQueue);

            print "---->locked\n";
                    $DQueue->enqueue($iElement);
            insertdata();

        }

        print "lock released\n";

    };
}

sub insertdata
{
     my $count=0;
     while ($DataElement = $DQueue->peek($count) )
     {
    print "-- position $count\n";
    $count++;
     }
}
+2  A: 

Perhaps the problem is that you use $DataQueue one place but $DQueue elsewhere? Make sure you are using strict and warnings.

If $iElement may be false (e.g. 0), you will need to say

while ( defined ( my $DataElement = $DQueue->peek($count) ) )

Correcting the variable name and putting in some code to call updateData, everything seemed to work for me.

ysth
Furthermore the queue manages its locking on its own, thus there is a risk of deadlocks by adding additional locking.
weismat
@weismat: Thread::Queue explicitly supports this type of locking to cover multiple operations on the queue with one lock, at least per the doc.
ysth
A: 

Here Is the answer

use Thread qw(async); 
use Thread::Queue;

 my $DataQueue:shared = new Thread::Queue; 

 $newElement = init($user,$param,$reqest);  # init is method in ElementStructure.pm
 #after creating the element it is passes to subroutine where thread is started

 my $th=new Thread(\&updateData);
 $th->join();

sub updateData
{

        {
            lock($DQueue);

            print "---->locked\n";
                    $DQueue->enqueue($newElement);
            insertdata();

        }

        print "lock released\n";

}

sub insertdata
{
     my $count=0;
     while ($DataElement = $DQueue->peek($count) )
     {
    print "-- position $count\n";
    $count++;
     }
}
kkchaitu