#!/usr/bin/perl

use strict;
use warnings;

use threads;
use Scalar::Util 'weaken';

use Test::More 'tests' => 2;


# My object class
package My::Obj; {
    my %reg;

    sub new
    {
        # Create object with ID = 1
        my $class = shift;
        my $id = 1;
        my $obj = bless(\do{ my $scalar = $id; }, $class);

        # Save weak copy of object for reference during cloning
        Scalar::Util::weaken($reg{$id} = $obj);

        # Return object
        Test::More::diag("Created object $id\n");
        return $obj;
    }

    # Return the internal ID of the object
    sub id
    {
        my $obj = shift;
        return ($$obj);
    }

    # During cloning 'look' at the object
    sub CLONE {
        foreach my $id (keys(%reg)) {
            Test::More::diag("Cloning object $id\n");

            # !!! If you comment out this line, tests pass !!!
            my $obj = $reg{$id};
        }
    }
}


# Run tests
package main;

# Create object in 'main' thread
my $obj = My::Obj->new();
is($obj->id(), 1, 'Got object ID in main');

# Access object in thread
threads->create(
    sub {
        is($obj->id(), 1, 'Got object ID in thread');
    }
)->join();

# EOF
