|
Boost : |
From: Phil Endecott (spam_from_boost_dev_at_[hidden])
Date: 2008-03-24 11:27:09
Frank Mori Hess wrote:
> On Sunday 23 March 2008 18:47 pm, Phil Endecott wrote:
>> The point is that all of the values share a mutex. Our Lockable<>
>> classes could be used here if you wanted one mutex per value, but that
>> could be wasteful and perhaps wrong. How can we adapt Lockable<> to
>> work in this sort of situation? I'm wondering about something like this:
>>
>> Lockable< array<int,100 > values;
>>
>> for (int i=0; i<100; ++i) {
>> start_updater(LockableRef<int>(values,values[i]);
>> }
>>
>> i.e. LockableRef contains a reference to the mutex and one element of
>> its "parent" Lockable<>, and presents the same interface as a data-full
>> Lockable<>.
>
> I think what you would want to do is just create one scoped lock, perhaps
> outside of the loop (a lock_acquirer in the lockable lib syntax) and use that
> to access the values in the array. It could just pass an ordinary reference
> to the start_updater function, as long as start_updater doesn't keep any
> persistent copies of the reference around.
No, I don't think so. You mean something equivalent to this:
mutex m;
array<int,100> values;
{
scoped_lock l(m);
for (int i=0; i<100; ++i) {
start_updater(LockableRef<int>(values,values[i]);
}
}
Right? That's not the scenario that I'm trying to describe.
> It could just pass an ordinary reference
> to the start_updater function, as long as start_updater doesn't keep any
> persistent copies of the reference around.
My point is that start_updater does keep a copy of the reference; from
my original post:
void start_updater(mutex& m, int& val)
{
// spawn a thread that periodically locks m and changes val
}
Or to be more explicit:
void run_updater(mutex& m, int& val)
{
while (1) {
sleep(1000);
scoped_lock l(m);
val = read_sensor();
}
}
void start_updater(mutex&m, int& val)
{
thread t(bind(run_updater,m,val));
}
Phil.
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk