А STM рулит, да. Не знаю, как в клозуре, а в хаскеле, где оно завернуто в специально обученную монаду, и потому сделать ошибку с ней крайне трудно, если вообще возможно, так удобно между тредами информацию гонять...
btw, вот неплохая статья про stm/clojure. а так, если соберешься книжку читать какую-нибудь, то рекомендую Clojure Programming by O'Reilly, она хоть и толстая, но хорошая :-)
Единственное, работает она очень медлено - это и проблема текущей реализации (еще не достаточно зрелая) и концептуальная (нужен хэш блокировок, адресуемый по адресам памяти, аналогично транзакциям в БД).
"I chose not to use the Erlang-style actor model for same-process state management in Clojure for several reasons:
- It is a much more complex programming model, requiring 2-message conversations for the simplest data reads, and forcing the use of blocking message receives, which introduce the potential for deadlock. Programming for the failure modes of distribution means utilizing timeouts etc. It causes a bifurcation of the program protocols, some of which are represented by functions and others by the values of messages. - It doesn't let you fully leverage the efficiencies of being in the same process. It is quite possible to efficiently directly share a large immutable data structure between threads, but the actor model forces intervening conversations and, potentially, copying. Reads and writes get serialized and block each other, etc. - It reduces your flexibility in modeling - this is a world in which everyone sits in a windowless room and communicates only by mail. Programs are decomposed as piles of blocking switch statements. You can only handle messages you anticipated receiving. Coordinating activities involving multiple actors is very difficult. You can't observe anything without its cooperation/coordination - making ad-hoc reporting or analysis impossible, instead forcing every actor to participate in each protocol. - It is often the case that taking something that works well locally and transparently distributing it doesn't work out - the conversation granularity is too chatty or the message payloads are too large or the failure modes change the optimal work partitioning, i.e. transparent distribution isn't transparent and the code has to change anyway."
лагко - кто-то принимает одну модель, а кто-то - другую. Для меня акторы более интересная тема, потому что она ближе к реальному миру, а не к базам данных - транзакционные состояния, все дела. Обмен же сообщениями является более чистым (на мой взгляд) функциональным подходом - в теории, а на практике (я думаю) - гораздо больше имеет шансов для горизонтальной масштабируемости. Я с удовольствием использую параллельные примитивы и средства синхронизации и STM - это из той же области компьютерной науки, только с синтаксическим сахаром. Так что я выбираю новое веяние, just for fun в том числе
а, ну тут автор прямо в лоб говорит - двунаправленная передача данных в одном процессе. Это очень скучный (и не очень частый в моей практике) вариант, для него в скале свои альтернативы и акторы там не нужны. Это как сравнивать Hello World на консоли и в веб приложении.
no subject
Date: 2012-11-09 04:45 pm (UTC)А STM рулит, да. Не знаю, как в клозуре, а в хаскеле, где оно завернуто в специально обученную монаду, и потому сделать ошибку с ней крайне трудно, если вообще возможно, так удобно между тредами информацию гонять...
no subject
Date: 2012-11-09 04:49 pm (UTC)no subject
Date: 2012-11-09 06:06 pm (UTC)no subject
Date: 2012-11-09 07:05 pm (UTC)no subject
Date: 2012-11-09 07:11 pm (UTC)no subject
Date: 2012-11-10 10:52 am (UTC)no subject
Date: 2012-11-10 11:04 am (UTC)no subject
Date: 2012-11-10 12:53 pm (UTC)Относительно недавно писал про STM в GCC: http://natsys-lab.blogspot.ru/2012/05/software-transactional-memory-stm-in.html . В процессорах следующего поколения от Intel уже будет аппаратная поддержка.
Единственное, работает она очень медлено - это и проблема текущей реализации (еще не достаточно зрелая) и концептуальная (нужен хэш блокировок, адресуемый по адресам памяти, аналогично транзакциям в БД).
no subject
Date: 2012-11-10 04:28 pm (UTC)no subject
Date: 2012-11-11 09:39 pm (UTC)а про STM - акторы наше всё
Прокомментируй?
Date: 2012-11-12 05:49 am (UTC)- It is a much more complex programming model, requiring 2-message conversations for the simplest data reads, and forcing the use of blocking message receives, which introduce the potential for deadlock. Programming for the failure modes of distribution means utilizing timeouts etc. It causes a bifurcation of the program protocols, some of which are represented by functions and others by the values of messages.
- It doesn't let you fully leverage the efficiencies of being in the same process. It is quite possible to efficiently directly share a large immutable data structure between threads, but the actor model forces intervening conversations and, potentially, copying. Reads and writes get serialized and block each other, etc.
- It reduces your flexibility in modeling - this is a world in which everyone sits in a windowless room and communicates only by mail. Programs are decomposed as piles of blocking switch statements. You can only handle messages you anticipated receiving. Coordinating activities involving multiple actors is very difficult. You can't observe anything without its cooperation/coordination - making ad-hoc reporting or analysis impossible, instead forcing every actor to participate in each protocol.
- It is often the case that taking something that works well locally and transparently distributing it doesn't work out - the conversation granularity is too chatty or the message payloads are too large or the failure modes change the optimal work partitioning, i.e. transparent distribution isn't transparent and the code has to change anyway."
Re: Прокомментируй?
Date: 2012-11-12 05:56 am (UTC)Я с удовольствием использую параллельные примитивы и средства синхронизации и STM - это из той же области компьютерной науки, только с синтаксическим сахаром. Так что я выбираю новое веяние, just for fun в том числе
Re: Прокомментируй?
Date: 2012-11-12 06:00 am (UTC)