[Vala] Threads, synchronization & locking
- From: Frederik <scumm_fredo gmx net>
- To: vala-list gnome org
- Subject: [Vala] Threads, synchronization & locking
- Date: Tue, 02 Dec 2008 20:12:41 +0100
Hi,
I have been experimenting with threads & synchronization in Vala with
the Dining Philosophers Problem [1] (see attachment). If I want to lock
a mutex I have to use:
mutex.lock ();
// ...
mutex.unlock ();
If i use
lock (mutex) {
// ...
}
another mutex is created instead of locking the given one. Would it make
sense to lock the mutex itself if the lock object is of type Mutex
instead of creating a new one?
Regards,
Frederik
[1] http://en.wikipedia.org/wiki/Dining_philosophers_problem
// Dining Philosophers
// Compile with 'valac --thread philosophers.vala'
class Forks {
private bool[] fork = new bool[5];
private Cond cond = new Cond ();
private Mutex mutex = new Mutex ();
public void pick_up (int left, int right) {
mutex.lock ();
while (fork[left] || fork[right]) {
cond.wait (mutex);
}
fork[left] = true;
fork[right] = true;
mutex.unlock ();
}
public void lay_down (int left, int right) {
mutex.lock ();
fork[left] = false;
fork[right] = false;
cond.broadcast ();
mutex.unlock ();
}
}
class Philosopher {
private int number;
private int think_delay;
private int eat_delay;
private int left;
private int right;
private Forks forks;
public Philosopher (int number, int think_delay, int eat_delay, Forks forks) {
this.number = number;
this.think_delay = think_delay;
this.eat_delay = eat_delay;
this.forks = forks;
this.left = number == 0 ? 4 : number - 1;
this.right = (number + 1) % 5;
}
public void* run () {
while (true) {
Thread.usleep (think_delay);
forks.pick_up (left, right);
stdout.printf ("Philosopher %d is eating...\n", number);
Thread.usleep (eat_delay);
forks.lay_down (left, right);
}
}
}
static int main (string[] args) {
if (!Thread.supported ()) {
error ("Cannot run without thread support.");
}
var forks = new Forks ();
Philosopher[] philos = {
new Philosopher (0, 100000, 500000, forks),
new Philosopher (1, 200000, 400000, forks),
new Philosopher (2, 300000, 300000, forks),
new Philosopher (3, 400000, 200000, forks),
new Philosopher (4, 500000, 100000, forks)
};
try {
foreach (var philosopher in philos) {
Thread.create (philosopher.run, false);
}
} catch (ThreadError e) {
error ("%s\n", e.message);
}
new MainLoop (null, false).run ();
return 0;
}
[
Date Prev][
Date Next] [
Thread Prev][
Thread Next]
[
Thread Index]
[
Date Index]
[
Author Index]