Re: initialize a mutex into locked state?
From: Oleg Drokin
Date: Fri Jun 17 2016 - 10:46:21 EST
The problem is if you are not holding the spinlock, some parallel thread might have added a structure into the
list that makes our no longer needed. So upon spinlock reacquisition we'll need to do another lookup, find
the now added structure and throw ours away - even more expensive.
On Jun 17, 2016, at 10:32 AM, Matthew Jacob wrote:
> At the risk of sounding annoying, the problem here isn't in the locking but in the flow.
> If the structure already exists, spinlock is fine. Return after dropping spinlock.
>
> If the structure doesn't exist, you can drop the spinlock to create it (and initialize the lock &and& grab the lock, should you want to) *prior* to adding it to the list because nobody else could know about it until you put it on the list.
>
> On Fri, Jun 17, 2016 at 7:24 AM, Oleg Drokin <green@xxxxxxxxxxxxxx> wrote:
>
> On Jun 17, 2016, at 10:19 AM, Peter Zijlstra wrote:
>
> > On Fri, Jun 17, 2016 at 10:14:10AM -0400, Oleg Drokin wrote:
> >>
> >> On Jun 17, 2016, at 4:25 AM, Peter Zijlstra wrote:
> >>
> >>> On Wed, Jun 15, 2016 at 02:23:35PM -0400, Oleg Drokin wrote:
> >>>> Hello!
> >>>>
> >>>> To my surprise I found out that it's not possible to initialise a mutex into
> >>>> a locked state.
> >>>> I discussed it with Arjan and apparently there's no fundamental reason
> >>>> not to allow this.
> >>>
> >>> There is. A mutex _must_ have an owner. If you can initialize it in
> >>> locked state, you could do so statically, ie. outside of the context of
> >>> a task.
> >>
> >> What's wrong with disallowing only static initializers, but allowing dynamic ones?
> >> Then there is a clear owner.
> >
> > At which point, what wrong with the simple:
> >
> > mutex_init(&m);
> > mutex_lock(&m);
> >
> > Sequence? Its obvious, has clear semantics and doesn't extend the API.
>
> The problem is:
>
> spin_lock(somelock);
> structure = some_internal_list_lookup(list);
> if (structure)
> goto out;
>
> init_new_structure(new_structure);
> mutex_init(&new_structure->s_mutex);
> mutex_lock(&new_structure->s_mutex); // XXX CANNOT DO THIS UNDER SPINLOCK!
>
> list_add(list, new_structure->s_list);
> structure = new_structure;
> out:
> spin_unlock(somelock);
> return structure;
>
>