develooper Front page | perl.ithreads | Postings from August 2002

Re: Goodbye to threads

Thread Previous | Thread Next
From:
Dave Mitchell
Date:
August 20, 2002 05:06
Subject:
Re: Goodbye to threads
Message ID:
20020820130358.M7231@fdgroup.com
On Tue, Aug 20, 2002 at 12:09:32PM +0200, Elizabeth Mattijsen wrote:
> And all of this is caused by the fact that cond_signal just _wakes_ the
> thread in cond_wait, so it can join in the fight for the lock.  In my
> opinion, the thread being woken should _always_ _immediately_ get the
> lock (in the case of cond_signal).  And if you are using cond_broadcast,
> _one_ of the threads being woken should get the lock.  Currently all of
> the woken threads join in the fight for the lock.

But that's the way the underlying OS's cond_wait() stuff typically works
(eg try 'man cond_wait').

The trick is to have two condition variables. The first arbitrates access
by the clients to the second variable. The second is then used by the
one lucky client to signal the server.
For example, something along the lines of:

    # condition variables
    my $client : shared;
    my $server : shared;

    sub server {
	lock ($server);
	while (1) {
	    cond_wait($server); # wait for request
	    # ... do something ...
	    cond_signal($server); # say we've finished
	}
    }

    sub client {
	while (1) {
	    # ... prepare a request ...
	    lock($client); # make me the privileged client
	    lock($server);
	    cond_signal($server); # wake up the server
	    cond_wait($server); # yield, then wait for the server to finish
	}

    }
The extra variable $client ensures that only the server and *one* client
are trying to lock $server. The extra wait/sig on $server at the end of
each function is to ensure that it is the server that re-acquires the $server
lock, not one of the clients.

Note that there are no yield()'s here at all.  In general, needing a
yield() in code implies that you're doing something wrong, and that you
need to add more condition variables and waits and sigs.

Hope this helps,

Dave.

-- 
"But Sidley Park is already a picture, and a most amiable picture too.
The slopes are green and gentle. The trees are companionably grouped at
intervals that show them to advantage. The rill is a serpentine ribbon
unwound from the lake peaceably contained by meadows on which the right
amount of sheep are tastefully arranged." Lady Croom - Arcadia

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About