🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Thread View: pl.comp.lang.perl
1 messages
1 total messages Started by =?UTF-8?B?SmFyb3 Wed, 13 Jun 2012 21:24
threads::shared a wspóødzielenie zmiennych
#51331
Author: =?UTF-8?B?SmFyb3
Date: Wed, 13 Jun 2012 21:24
105 lines
1993 bytes
Środowisko:
CentOS 5.8, perl 5.8.8

Mam taki sobie kod:


#!/usr/bin/perl
use strict;
use warnings;

use threads;
use threads::shared;

my $v1 : shared = 0;

my $threadsmp1 = threads->create( \&th1);
my $threadsmp2 = threads->create( \&th2);

my $v2 : shared = 0;

sub to_str
{
     my $v = shift;
     defined( $v) ? $v : 'undef!';
}

sub th1
{
     while( 1)
     {
         {
             lock( $v1);
             $v1++; $v2++;
             print( 'th1: v1=', to_str( $v1), " v2=", to_str( $v2), "\n");
         }
         sleep 1;
     }
}

sub th2
{
     while( 1)
     {
         {
             lock( $v1);
             print( 'th2: v1=', to_str( $v1), " v2=", to_str( $v2), "\n");
         }
         sleep 1;
     }
}

while( 1)
{
     sleep 1;
}

__END__


Jak widać program w jednym wątku inkrementuje zmienne współdzielone $v1
i $v2 oraz wypisuje ich wartość poprzez procedurę to_str, w drugim tylko
wypisuje zmienne ustawione przez pierwszy wątek.

Powinniśmy jak sądzę dostać na wyjściu coś w rodzaju:

th1: v1=1 v2=1
th2: v1=1 v2=1
th1: v1=2 v2=2
th2: v1=2 v2=2
th1: v1=3 v2=3
th2: v1=3 v2=3
..............

Tymczasem program wypisuje:

th1: v1=1 v2=1
th2: v1=1 v2=undef!
th1: v1=2 v2=2
th2: v1=2 v2=undef!
th1: v1=3 v2=3
th2: v1=3 v2=undef!
...............

Różnica jest taka, że $v2 jest zadeklarowana *po* utworzeniu obu wątków
i w efekcie przypisania ustawione przez jeden wątek nie są widoczne w
drugim. Czemu tak jest? Czy naprawdę wszystkie zmienne współdzielone
muszę zadeklarować *przed* utworzeniem wątków, które z nich korzystają?

Nie doczytałem się nic na ten temat w
http://search.cpan.org/~jdhedden/threads-shared-1.40/lib/threads/shared.pm

threads 1.86, threads::shared 1.40 (najnowsze wersje pakietów)

Czego nie rozumiem?

--
Pozdrawiam
Jarek Lubczyński
(eljot<NULL>90125 at gmail dot com)
Nawiasy trójkątne z zawartością zbędne są

There are 10 kinds of people:
Those who understand binary and those who don't


Thread Navigation

This is a paginated view of messages in the thread with full content displayed inline.

Messages are displayed in chronological order, with the original post highlighted in green.

Use pagination controls to navigate through all messages in large threads.

Back to All Threads