Question about threads::shared and blessed references

Discussion in 'Perl' started by Nick Marden, Jan 17, 2004.

  1. Nick Marden

    Nick Marden Guest

    I am trying to use threads::shared to make a thread-safe object.

    It appears to be the case that copying a blessed-then-shared reference
    to another shared variable keeps the underlying structure intact
    (e.g., hashref & its contents) but forgets the blessedness. This makes
    my program pretty useless because I need to be able to copy or pass my
    lockable object(s) at various times in my program, without losing
    their identity as blessed objects.

    The attached program demonstrates what I am trying to say. It's output

    ref $f = LockableObject
    ref $copy = HASH

    Note that there are no threads involved here; this is all executing in
    a single thread.

    Also note that if you remove the share() call from
    LockableObject::new(), make $copy a non-shared variable, and comment
    out the *LOCK_BLOCK blocks - in other words, if you remove just the
    threadedness of the program - then the program works "right". In this
    case the output is what I had originally expected, to wit:

    ref $f = LockableObject
    ref $copy = LockableObject

    What am I missing?

    (P.S. perl -V says "Summary of my perl5 (revision 5.0 version 8
    subversion 0)...usethreads=define use5005threads=undef
    useithreads=define usemultiplicity=define" and a bunch of other things
    that are available upon request if they are relevant.)
    #!/usr/bin/perl -w

    use strict;

    package LockableObject;

    use threads;
    use threads::shared;

    sub new {
    my $obj = bless { }, shift;
    # Imagine that $obj has some internals that I want to protect,
    # so I need to be able to lock the object to serialize access

    package main;

    use threads;
    use threads::shared;

    my $f = new LockableObject;

    print "ref \$f = ", ref $f, "\n";

    # The object is lockable. Look, no errors!
    lock ($f);

    my $copy : shared = $f;

    # The copy of the object is still lockable!
    lock ($copy);

    # But the copy is no longer a LockableObject reference
    print "ref \$copy = ", ref $copy, "\n";

    Nick Marden, Jan 17, 2004
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.