Lists Perl Org wrote: > Hi all, > > I'm quite new to Perl so please bear with me :) > > I've experience in Delphi so I thought I knew about objects... it > seems I don't :( > > I want to have a class I won't instanciate (static members and > variables), with global vars so I can access them and change them from > withing threads/forks.
not sure what you mean by that but looks like you want to have a global variable where the threads can manipulate and all the threads will see the same value once a thread modified the vairable. if so you need to lock the variable before letting the threads to access that variable. > > -- FILE test.pl > > use FOO; > > FOO->make(); > FOO->make(); > > use Thread; > > my $t = new Thread \&th1; > my $u = new Thread \&th2; > > sub th1() { while (1) { FOO->make(); sleep(1); } } > sub th2() { while (1) { print "\t"; FOO->make(); sleep(2); } } threads->yield is usually a better choice to than sleep if you want the OS to know that it should pay attention to another thread. > > while (1) {} > > -- FILE FOO.pm > > package FOO; > > %FOO::e = {}; > > sub make { > my $self = shift; > %FOO::e->{'something'} = %FOO:e->{'something'} + 1; > print %FOO::e->{'something'}."\n"; > } > > -- RESULTS -- > > 1 > 2 > 3 > 3 > 4 > 5 > 4 > 6 > 7 > 5 > 8 > ... > > Obviously it doesn't work. > > I have tried a lot more of things and I don't know how to make it > work. The same applies if I use fork() instead threads. forking a different process is different than making a new thread. obviously, very little is shared between a parent and a child process which makes sharing a global variables before multiple process a bit difficult. > > Is there any way to make this work? > if i understand your question correctly, see if the following helps: #!/usr/bin/perl -w use strict; use threads; use threads::shared; package AnotherNameSpace; #-- #-- $var is global to AnotherNameSpace and will #-- be shared among all threads #-- my $var : shared = 1; sub inc{ #-- #-- let only one thread access $var at a time #-- { lock($var); $var++; print STDERR "$_[0]$var\n"; } } package main; sub get1{ while(1){ AnotherNameSpace::inc(''); threads->yield; } } sub get2{ while(1){ AnotherNameSpace::inc("\t"); threads->yield; } } my $t1 = threads->new(\&get1); my $t2 = threads->new(\&get2); $t1->join; $t2->join; __END__ prints: 10 11 12 13 14 15 ... 538 539 540 541 542 543 ... lines begin with a tab is printed by one thread and those that do not being with the tab are printed by another thread. as you can see, they all syn up. without the locking, you might see something like: 601 598 602 599 603 600 604 601 which probably isn't what you expect. david -- $_=q,015001450154015401570040016701570162015401440041,,*,=*|=*_,split+local$"; map{~$_&1&&{$,<<=1,[EMAIL PROTECTED]||3])=>~}}0..s~.~~g-1;*_=*#, goto=>print+eval -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]