strange unexpected deadlock Hi,
I'm trying to make myself familiar with threads.

However, I encountered some unexpected behaviour of locks/cond_wait I wasn't 
able to figure out.
Could someone explain to me what's happening ??
Thanks, Michael


---------------------- 

#!/usr/bin/perl -w
use threads;
use threads::shared;

share( $x );
share( $y );

sub thread1{
		print "1\\n";
		lock $x;
		print "locked x: 1\\n";
		cond_wait $x;
		print "thread1\\n";
		lock $y;
		cond_signal $y;
		print "t1\\n";
}

sub thread2{
		sleep 1;
		lock $y;
#		{ 
			lock $x;
			print "locked x: 2\\n";
			cond_signal $x;
#		}
		print "thread2\\n";
		sleep 1;
		cond_wait $y;
		print "t2\\n";
}

my $t1 = threads->create( "thread1" );
my $t2 = threads->create( "thread2" );

$t1->join;
$t2->join;

print "exit.\\n";

---------------------


I expected the script to have a output like:
---
1
locked x: 1
locked x: 2
thread2
thread1
t1
t2
exit.
---
Instead it hangs in the function thread1, at cond_wait $x,
so here's the actual output.
---
1
locked x: 1
locked x: 2
thread2
---

If I uncomment the two brackets of the function thread2, it works again. Which 
I cannot understand.

---
sub thread2{
		sleep 1;
		lock $y;
		{ 
			lock $x;
			print "locked x: 2\\n";
			cond_signal $x;
		}
		print "thread2\\n";
		sleep 1;
		cond_wait $y;
		print "t2\\n";
}






-- 
To unsubscribe, e-mail: beginners-unsubscribe@perl.org
For additional commands, e-mail: beginners-help@perl.org
http://learn.perl.org/


