Изменение блокировки возражает внутри @synchronized разделу

Обратные вызовы в C обычно реализуются с помощью указателей функции и связанного указателя данных. Вы передаете свою функцию on_event() и указатели данных на функцию платформы watch_events() (например). Когда случай происходит, Ваша функция вызвана с Вашими данными и некоторыми определенными для события данными.

Обратные вызовы также используются в программировании GUI. GTK + учебное руководство имеет хороший раздел по теория сигналов и обратных вызовов .

6
задан Borys Verebskyi 24 February 2016 в 20:50
поделиться

1 ответ

Short answer: no, they won't properly lock/unlock, and such approaches should be avoided.

My first question is why you'd want to do something like this, since these approaches nullify the purposes and benefits of using a @synchronized block in the first place.

In your second example, once a thread changes the value of obj, every subsequent thread that reaches the @synchronized block will synchronize on the new object, not the original object. For N threads, you'd be explicitly creating N autoreleased objects, and the runtime may create up to N recursive locks associated with those objects. Swapping out the object on which you synchronize within the critical section is a fundamental no-no of thread-safe concurrency. Don't do it. Ever. If multiple threads can safely access a block concurrently, just omit the @synchronized entirely.

In your first example, the results may be undefined, and certainly not what you want, either. If the runtime only uses the object pointer to find the associated lock, the code may run fine, but synchronizing on nil has no perceptible effect in my simple tests, so again you're using @synchronized in a pointless way, since it offers no protection whatsoever.

I'm honestly not trying to be harsh, since I figure you're probably just curious about the construct. I'm just wording this strongly to (hopefully) prevent you and others from writing code that is fatally flawed, especially if under the assumption that it synchronizes properly. Good luck!

9
ответ дан 10 December 2019 в 02:51
поделиться
Другие вопросы по тегам:

Похожие вопросы: