Министерство общего и профессионального образования Российской Федерации _________________________ Пензенский государств...
9 downloads
207 Views
693KB Size
Report
This content was uploaded by our users and we assume good faith they have the permission to share this book. If you own the copyright to this book and it is wrongfully on our website, we offer a simple DMCA procedure to remove your content from our site. Start by pressing the button below!
Report copyright / DMCA form
Министерство общего и профессионального образования Российской Федерации _________________________ Пензенский государственный технический университет __________________________________________________
В. Н. Дубинин, С. А. Зинкин
ЯЗЫКИ ЛОГИЧЕСКОГО ПРОГРАММИРОВАНИЯ В ПРОЕКТИРОВАНИИ ВЫЧИСЛИТЕЛЬНЫХ СИСТЕМ И СЕТЕЙ Учебное пособие
Пенза 1997
УДК 681.3.06 : 519.68 Д 79 Дубинин В. Н. Зинкин С.А. Языки логического программирования в проектировании вычислительных систем и сетей: Учеб. пособие. - Пенза: Изд-во Пенз. гос. техн. ун-та, 1997. - 100 с.: 18 ил., библиогр. 64 назв. Рассматриваются вопросы использования языка логического программирования Пролог в сетевой технологии проектирования распределенных вычислительных систем и сетей. Приводится описание предикатных сетей, интерпретируемых на языке Пролог, примеры спецификации и моделирования вычислительных систем, процессов и сетевых протоколов с использованием данного сетевого формализма. Представлено описание временной логики для верификации вычислительных систем и процессов, подробно описана реализация временных операторов на Прологе, приводятся примеры формулировки и доказательства свойств рассмотренных в пособии вычислительных систем, процессов и сетевых протоколов. Учебное пособие подготовлено на кафедре "Вычислительная техника" и предназначено для студентов специальности 22.01.00, изучающих дисциплины "Языки логического программирования", "Вычислительные комплексы, системы и сети", "Системы искусственного интеллекта", "Прикладная математика". Рецензенты: кафедра "Прикладная математика и информатика" Пенз. гос. пед. ун-та им. В. Г. Белинского (зав. кафедрой - д-р техн. наук, проф. В. М. Линьков); В. М. Михайлов, д-р техн. наук, гл. инж. НИИВТ
Издательство Пензенского государственного технического университета, 1997
В. Н. Дубинин, С. А. Зинкин, 1997
Введение Идея использовать логику в качестве языка программирования возникла впервые в начале 70-х годов. Первыми исследователями, разрабатывавшими эту идею, были Роберт Ковальский (теоретические аспекты) и Маартен ван Эмдем (экспериментальная демонстрационная система). Наибольшую популярность из языков, основанных на логике, завоевал язык логического программирования Пролог. Название Пролог (PROLOG) образовано из первых частей английских слов PROgramming и LOGic, что означает программирование в терминах логики. Данный язык относится к языкам сверхвысокого уровня. Основные особенности языка: - является языком логического программирования. Теоретической основой Пролога является логика предикатов. Модель логической программы основана на подмножестве хорновских дизъюнктов логики предикатов; - в Прологе имеется мощный встроенный механизм логического вывода с поиском и возвратом, встроенный механизм сопоставления с образцом. В Пролог-системах реализован обратный вывод (от цели) методом поиска вглубь; - Пролог ориентирован на работу с символьной информацией; - в Прологе единообразно представляются программы и данные, что позволяет модифицировать программу во время ее работы; - Пролог поддерживает декларативный стиль программирования. Пролог-программы определяют "что" надо сделать, а не "как" это делается; - в Прологе существует как декларативная, так и процедурная семантика программ. В настоящее время не существует стандарта на Пролог. Все же реализация, описанная в книге [18], может быть принята за неофициальный стандарт ядра "чистого" Пролога. Известны ряд версий и реализаций языка Пролог, например, Arity Prolog, Turbo Prolog, CProlog, Quintus Prolog, Prolog2 и др. [11]. Возможна реализация Пролога на языке Лисп [52]. Области применения Пролога: - программная инженерия, быстрая разработка прототипов прикладных программ [18]; - создание динамических реляционных баз данных [19,22]; - быстрая разработка компиляторов [2,11,18,30]; - создание естественно-языковых интерфейсов [22]; - перевод с одного языка на другой; - представление знаний, реализация экспертных систем (ЭС) и оболочек ЭС [6,11,19,36];
- создание пакетов символьных вычислений для решений уравнений, дифференцирования и интегрирования; - автоматическое доказательство теорем и системы искусственного интеллекта [6]; - управление производственными процессами. Можно отметить, что в зарубежной и отечественной литературе незаслуженно мало внимания уделено использованию языка Пролог в проектировании. Внедрение методов искусственного интеллекта в процесс проектирования, усложнение процедур поиска решений несомненно повысят интерес к Прологу. Данное учебное пособие посвящено использованию языка Пролог в проектировании вычислительных систем и сетей в рамках сетевой технологии проектирования. Под сетевой технологией понимается технология проектирования на основе сетевых моделей, берущих свое начало от хорошо известных сетей Петри (СП) [23]. На рис. 1 приведена схема сетевой технологии проектирования распределенных вычислительных систем (РВС), разработанной авторами учебного пособия. На данном рисунке прямоугольниками с прямыми углами представляется начальный, конечный или промежуточные результаты, а прямоугольниками с округленными краями - действия (этапы) технологической цепочки. Разработан ряд программных инструментальных средств, поддерживающих те или иные этапы данной технологии. К ним можно отнести системы СИМС, СИМС-М, комплекс программ СИМСГРАФ, а также библиотеку программ "Распределенная обработка - 1" (РО-1). Аппаратной платформой для реализации РВС могут служить локальные сети типа Ethernet на основе персональных ЭВМ, совместимых с IBM PC, а также глобальная сеть Internet, предоставляющая разработчику широкий спектр коммуникационных услуг. В обозначениях действий на рис. 1 в круглых скобках отмечены те программные средства, которые поддерживают данное действие технологической цепочки. В данном случае под обозначением WWW понимаются средства гипертекстовой технологии WWW (World Wide Web) глобальной сети Internet. Если для какого-либо этапа не отмечены программные средства, то это означает, что в настоящий момент данный этап не автоматизирован и действия должны производиться разработчиком вручную. Из приведенной схемы видны место и роль языка Пролог в сетевой технологии. В данном случае Пролог и средства, разработанные на его основе, используются для спецификации и верификации систем, а также для интерпретации результатов исследования сетевых моделей. Реализация этапа интерпретации результатов сопряжена со следующими трудностями: неформализованностью или слабой формализованностью данного этапа, неинтерпретированностью сетевой модели. Последняя трудность выражается в необходимости проекции свойств сетевой модели на свойства системы.
Этап интерпретации результатов исследования проводится с использованием методов искусственного интеллекта, а автоматизация данного этапа - с привлечением ЭС, реализованной на языке Пролог.
Ðèñ.1.Ñåòåâàÿ òåõíîëîãèÿ ïðîåêòèðîâàíèÿ ðàñïðåäåëåííûõ âû÷èñëèòåëüíûõ ñèñòåì В первой главе учебного пособия дано краткое описание предикатных сетей, интерпретируемых на языке Пролог. Использование этого сетевого формализма позволяет в значительной мере сократить и формализовать описание параллельных систем со сложными видами межпроцессных взаимодействий. Для спецификации и моделирования параллельных взаимодействующих интеллектуальных систем предлагается модификация предикатных сетей, связанная с введением структурированных меток, меток с атрибутами-переменными, а также с использованием способности к саморазвертыванию и самоизменению сетевой модели [37]. Примеры спецификации и моделирования вычислительных систем и процессов с использованием предикатных сетей представлены во второй главе. Приводится достаточно полное описание ряда типовых задач синхронизации: задачи взаимного исключения, задачи об обедающих философах, а также задачи некорректного разделения общих ресурсов. Дается конечноавтоматное представление результатов моделирования алгоритма взаимного исключения в распределенной вычислительной системе и альтернативно-битового протокола. В третьей главе представлено описание особенностей построения языка временной логики, используемого для исследования сетевых моделей. В пособии подробно описывается реализация временных операторов и приводятся примеры формулировки и доказательства свойств рассмотренных в пособии вычислительных систем и сетей.
1. МОДЕЛИРОВАНИЕ ПАРАЛЛЕЛЬНЫХ ДИСКРЕТНЫХ СИСТЕМ С ИСПОЛЬЗОВАНИЕМ ПРЕДИКАТНЫХ СЕТЕЙ, ИНТЕРПРЕТИРУЕМЫХ НА ЯЗЫКЕ ПРОЛОГ В данной главе рассматривается метод моделирования параллельных дискретных систем с помощью высокоуровневых сетей Петри, интерпретируемых на языке Пролог. Данный класс систем характеризуется: 1) параллельным и асинхронным функционированием компонентов системы; 2) наличием сложных межкомпонентных взаимодействий и 3) дискретным изменением параметров системы при ее работе. Примеры подобных систем можно найти в технике и экономике. Весьма показательным примером являются вычислительные сети и распределенные вычислительные системы (РВС). РВС - это полносвязная целевая система, представляющая совокупность обрабатывающих узлов с распределенными по ним данными, процессами обработки информации и управления и взаимодействующих через каналы связи путем обмена сообщениями. Динамика работы РВС характеризуется параллельностью и асинхронностью протекающих в системе процессов, сложностью межпроцессных взаимодействий. РВС могут быть реализованы на основе сети ЭВМ, предоставляющей пользователю широкий круг коммуникационных услуг. Основой архитектуры вычислительных сетей и РВС являются коммуникационные протоколы (КП) - наборы правил взаимодействия систем на различных уровнях иерархии. Протоколы определяют многие важные аспекты работы сетей: надежность доставки данных, количество и качество услуг, совместимость с другими сетями. Пристальный интерес к протоколам и полученные в последние годы результаты позволяют говорить о формировании новой научной дисциплины. Для точного и однозначного описания КП разрабатываются методы формального описания. Модели, лежащие в основе того или иного метода формального описания, позволяют выполнить анализ (верификацию) описаний, а также автоматизировать процесс трансляции этих описаний непосредственно в реализацию. Анализ работ по протокольной тематике показал, что в качестве основы языков и методов формального описания использовался самый разнообразный математический аппарат [26,27,28,35]. Среди многих существующих методов моделирования сложных параллельных дискретных систем выделяется подход, основанный на использовании сетевых моделей, берущих свое начало от сетей Петри (СП) [23]. Сетевые модели имеют следующие преимущества:
1) большие выразительные способности в представлении параллельных асинхронных систем; способность представления локального управления, параллельных, конфликтных, недетерминированных и асинхронных событий; графическое представление сети; понятность модели и легкость ее изучения; 2) возможность иерархического моделирования на их основе; неинтерпретированность сетевой модели; возможность описания системы на различных уровнях абстракции; возможность представления системной иерархии; 3) возможность машинной поддержки в проектировании; недетерминированность реализации сетевой модели; наличие методов аналитического исследования сетевой модели. В дальнейшем для моделирования параллельных дискретных систем будут использоваться сети «предикат-переход» (Predicat/Transition Net) [32], называемые в дальнейшем просто предикатными сетями. Причиной введения предикатных сетей явилась необходимость компактного представления больших и сложных систем без потери формальных основ сетей Петри, на базе которых они разработаны. Для каждой предикатной сети может быть построена уникальная сеть Петри, эквивалентная ей в том смысле, что она моделирует ту же самую систему. С другой стороны, существует множество возможностей свернуть сеть Петри в эквивалентную ей предикатную сеть. Сжатость представления с помощью предикатной сети объясняется тем, что элементы предикатной сети - переходы, позиции и дуги представляют целый класс элементов эквивалентной сети Петри. Количественно и качественно переход от сетей Петри к предикатным сетям сравним с переходом от логики высказываний к логике предикатов первого порядка. Также как и цветные сети Петри, предикатные сети относятся к высокоуровневым сетям Петри. Эти два вида сетевых моделей близки друг другу и являются взаимозаменяемыми. Существует тесная связь между предикатными сетями и логическим программированием. Любую логическую программу, представленную набором хорновских дизъюнктов (например, Пролог-программу), можно представить в виде предикатной сети и использовать при верификации программы методы анализа сетевых моделей. В данной главе рассматривается интерпретация предикатных сетей на языке Пролог. В качестве инструментальной Пролог-системы используется интегрированная система Arity Prolog [22], разработанная фирмой Arity Corporation для РС-совместимых персональных ЭВМ и работающая под управлением операционной системы MS-DOS. В отличие от широко известного языка Turbo Prolog [8], также используемого при программировании на ПЭВМ, язык Arity Prolog обладает перед первым преимуществами в том плане, что он близок к классической Эдинбургской
версии языка Пролог и, таким образом, избавлен от ограничений языка Turbo Prolog, что позволяет более эффективно решать задачи спецификации и верификации. Синтаксис Arity Prolog аналогичен синтаксису DEC-10 Пролога [18]. Arity Prolog обладает следующими двумя особенностями, которые облегчают разработку больших программ: 1) наличие виртуальной памяти и 2) возможность разделения программы на сегменты.
1.1 Предикатные сети Предикатная сеть состоит из следующих компонентов [32]: 1) Ориентированной сети (Р, T, F), где Р – множество позиций; Т – множество переходов; F ⊆ P ×T ∪ T ×P – отношение потока. Позиции сети представляют предикаты, истинное значение которых определяется их маркировкой. 2) Структуры ∑, состоящей из множества индивидуальностей (цветов), операций и отношений. 3) Разметки всех дуг сети формальными суммами кортежей, составленных из переменных и индивидуальностей. Длина кортежа есть арность предиката, ассоциированного с дугой. Кортеж нулевой длины указывает на предикат без аргументов и обозначается специальным символом ⊄ . Примеры пометок дуг представлены на рис. 1.1,а. 4) Логических формул, приписанных некоторым переходам. Данные формулы строятся с помощью индивидуальностей, операций и отношений структуры ∑, а также переменных. Свободные переменные в формуле перехода должны встречаться на соседних дугах этого перехода. Истинность логической формулы влияет на возможность срабатывания перехода при данной маркировке. Примеры переходов с приписанными им логическими формулами приведены на рис. 1.1,б. Если формула, приписанная переходу, имеет форму v = trm & ..., где v – переменная и trm – терм, то все вхождения переменной v для данного перехода могут быть заменены на терм trm. (рис 1.2).
Ðèñ.1.1.Ýëåìåíòû ïðåäèêàòíîé ñåòè: a-ïîìå÷åííûå äóãè á-ïåðåõîäû ñ ëîãè÷åñêèìè ôîðìóëàìè; â-ìàðêèðîâàííûå ïîçèöèè.
Рис.1.2.Замена переменных на дугах перехода на терм: a-переход до замены; б-переход после замены.
5) Маркировки М0 позиций (предикатов) из Р формальными суммами кортежей, составленных из индивидуальностей структуры ∑. Данные кортежи будем называть метками. Примеры маркированных позиций представлены на рис. 1.1,в . 6) Функции К, назначающей позициям верхнюю границу числа меток, которые могут в них находиться. Число K(p) называется емкостью позиции р. Позиции могут иметь бесконечную емкость. В дальнейшем, если не будет оговорено особо, будем считать, что емкость позиций не ограничена. 7) Правил перехода, регламентирующих функционирование сетевой модели. Введем следующие определения. Для перехода ti ∈ T определим следующие множества: I(ti ) = {pj | pj ∈ P и (pj, ti ) ∈ F} – множество входных позиций перехода tj (пре-условия перехода ti); O(ti ) = {pj | pj ∈ P и (ti, pj) ∈ F} – множество выходных позиций перехода ti (пост-условия перехода ti ). Входными дугами перехода ti будем называть дуги, ведущие к этому переходу из позиций, принадлежащих множеству I(ti), а выходными – дуги, ведущие из перехода ti к позициям из O(ti). Подстановка σ есть отображение множества переменных V в множество индивидуальностей А, σ:V → A. Подстановка может быть задана множеством пар вида (x, σ(x)), где х ∈ V. Пусть X – кортеж и σ-подстановка. Кортеж σ[X] получается одновременной заменой всех вхождений переменных х в кортеже X на их образы σ(x). Кортеж Y называется конкретизацией кортежа X, если существует подстановка σ такая, что Y = σ [X]. При этом кортежи Y и X также будем называть сопоставимыми. Две подстановки σ1: V1→ A и σ2: V2 → A назовем не противоречащими друг другу, если ∀ v ∈ V1 ∧ V2 [σ1(v) = σ2(v)], т. е. если одним и тем же переменным обе подстановки ставят в соответствие одни и те же индивидуальности. В предикатной сети определены следующие условия разрешенности и правила срабатывания переходов. Переход ti ∈ Т разрешен, если: a) все позиции из множества I(ti ) имеют метки. Если пометка дуги (pk, ti ) представляет формальную сумму из m кортежей, то в позиции pk должно находиться по меньшей мере m меток. Для каждого кортежа, приписанного
входной дуге (pk, ti ), должна существовать такая подстановка σj, что в позиции pk будет метка, являющаяся конкретизацией данного кортежа. Иными словами, в позиции pk должна существовать сопоставимая с кортежом метка. Назовем подстановку σj сопоставляющей. Сопоставление различным кортежам одной и той же метки не допускается; б) существуют не противоречащие друг другу сопоставляющие подстановки для всех кортежей, приписанных входным дугам перехода ti. Объединение таких подстановок назовем общей сопоставляющей подстановкой; в) существует общая сопоставляющая подстановка, при которой логическая формула, приписанная переходу, становится истинной. Такую подстановку назовем разрешающей подстановкой; г) при добавлении соответствующего числа меток в выходные позиции не будет превышена емкость ни одной из них. Число добавляемых меток в выходную позицию определяется по числу кортежей в формальной сумме, помечающей выходную дугу. Сработать может только разрешенный переход. При срабатывании перехода ti метки из его входных позиций удаляются, а в выходные – добавляются. Число меток, удаляемых из позиции pk ∈ I(ti )), определяется числом кортежей, входящих в формальную сумму, приписанную дуге (pk, ti). Причем из позиции pk будут удалены только те метки, которые были сопоставлены кортежам из этой формальной суммы. Число меток, добавляемых в позицию pl ∈ O(ti ), определяется числом кортежей, входящих в формальную сумму, приписанную выходной дуге (ti, pl ). Добавляемые метки получаются путем конкретизации соответствующих кортежей с помощью разрешающей подстановки. Сетевая модель функционирует, переходя от одной маркировки к другой, начиная от начальной. Переход от маркировки М к маркировке M ′ в результате срабатывания перехода t обозначается как M t→ M ′ . Eсли t существуют переходы t1, t2,..., tn, такие, что Mi → M i +1 (i = 1,2,...,n) для маркировок M1, M2,..., Mn+1, то говорят, что Mn+1 достижима из M1 при последовательности срабатывания переходов σ = t1t2...tn . i
Проиллюстрируем функционирование предикатной сети на примерах. Рассмотрим сетевую модель, изображенную на рис. 1.3. Данная сетевая модель описывает часть семейных отношений, а именно, определяет отношение «Быть прародителем» (под «прародителем» понимается родитель родителя): «Субъект x является «прародителем» субъекта y, если x является родителем z, a z является родителем y». Если позиция «Родитель»
маркирована двумя метками <Юрий, Михаил> и <Евгений, Сергей>, то переход t неразрешен, так как не существует непротиворечащих сопоставляющих подстановок для кортежей <x, z> и . Если же позиция «Родитель» маркирована двумя метками <Юрий, Михаил> и <Михаил, Сергей>, то переход t является разрешенным. Разрешающая подстановка имеет следующий вид: {(x, Юрий), (y, Сергей), (z, Михаил)}. При срабатывании перехода t обе метки удаляются из позиции «Родитель», а в позицию «Прародитель» добавляется метка <Юрий, Сергей>. Появление данной метки в позиции «Прародитель» можно проинтерпретировать так: «Юрий является прародителем Сергея».
Ðèñ.1.3.Ñåòåâàÿ ìîäåëü, îïèñûâàþùàÿ ÷àñòü ñåìåéíûõ îòíîøåíèé Предикатная сеть, изображенная на рис. 1.4, используется для доказательства того, что Сократ смертен. Пусть позиция Р1 данной сетевой модели начально маркирована меткой <Сократ, грек>. При данной маркировке переход t2 неразрешен, а переход t1 – разрешен. При срабатывании перехода t1 метка <Сократ, грек> удаляется из позиции Р1, одновременно с этим в позицию Р1 добавляется метка <Сократ, человек>. Становится разрешенным переход t2. При срабатывании перехода t2 метка <Сократ, человек> удаляется из позиции Р1, одновременно с этим в позицию Р1 добавляется метка <Сократ, смертен>. Рассмотрим сетевую модель, представленную на рис. 1.5,а. Пусть задана структура ∑ = ({a,b,c}; :=), где := есть отношение упорядочения по алфавиту, и функция K: P → {3}. При данных условиях в представленной сетевой модели имеются две разрешающие подстановки. Из-за наличия конфликта может быть выбрана только одна из них. При выборе подстановки {(x,a), (y,b), (z,c)} результирующую маркировку, полученную в результате срабатывания перехода t1, можно увидеть на рис. 1.5,б.
Ðèñ.1.4.Ñåòåâàÿ ìîäåëü äëÿ äîêàçàòåëüñòâà ñìåðòíîñòè Ñîêðàòà
Ðèñ.1.5.Ïðèìåð ôóíêöèîíèðîâàíèÿ ñåòåâîé ìîäåëè: a-ñåòåâàÿ ìîäåëü äî ñðàáàòûâàíèÿ ïåðåõîäà; á-ñåòåâàÿ ìîäåëü ïîñëå ñðàáàòûâàíèÿ.
Следует отметить, что интерпретация предикатных сетей на языке Пролог способствует их модификации: внесению свойства саморазвертываемости и самомодифицируемости, структуризации набора цветов метки. При этом метка представляется в виде дерева, листьями которого являются цвета метки, а промежуточными вершинами – имена определенных подструктур. Корневая вершина дерева является именем метки. Соответствующим образом данное расширение касается пометки дуг и правил работы перехода. При желании можно перейти от иерархически структурированной метки к одноуровневому ее представлению. При этом имена подструктур преобразуются в цвета метки. Иерархически структурированную метку удобно представлять с помощью термов языка Пролог.
1.2. Некоторые свойства сетевых моделей Кратко рассмотрим некоторые свойства сетевых моделей. Обозначим через L(N,M) множество всех последовательностей срабатывания для сети N, начинающихся из маркировки М, через #(t,σ ) количество появлений символа t в последовательности σ, а через R(N,M) множество всех маркировок, достижимых из М. В качестве синонима термина «маркировка» в дальнейшем будем использовать также термин «состояние». Обозначим N ={1,2,...}. Позиция р сети N называется к-ограниченной, если ∀М’∈ R(N,M), M’(p) ≤ k. Сеть называется к-ограниченной, если все ее позиции кограничены. 1-ограниченную позицию (сеть) называют безопасной. ∀σ ∈ Переход t ∈ T живой при маркировке Mo в сети N, если L(N,Mo), ∃σ’ ∈ T [σσ’t ∈ L(N,Mo )] или ∀M’∈ R(N,Mo ), ∃M″ ∈ R(N,M’)[enable(t,M″)], где enable(t,M″) означает, что переход t разрешен при маркировке M″. Переход t ∈ T условно-живой при маркировке Мo в сети N, если ∀n ∈ N , ∃σ ∈ L(N,Mo ) [#(t,σ ) ≥ n]. Переход t ∈ T потенциально-живой при маркировке Мo в сети N, если ∃M’ ∈ R(N,Mo)∀ M’’ ∈ R(N,M’) M’’’ ∈ R(N,M″)[enable(t,M’’’)]. Переход t ∈ T частично-мертвый при маркировке Mo в сети N, если ∃n ∈ N , ∀σ ∈ L(N,Mo ) [#(t, σ )<=n]. Переход t ∈ T мертвый при маркировке Mo в сети N, если ∀σ L(N,Mo ) [#(t, σ )=0].
Сеть N - живая (условно-живая, частично-мертвая, мертвая) при маркировке M, если каждый ее переход живой (условно-живой, частично-мертвый, мертвый) при маркировке M. Маркировка M’ ∈ R(N,M ) называется тупиковой, если ∃ t ∈ T [enable(t,M )]. Можно выделить следующие основные методы исследования предикатных сетей, используемые при верификации: методы линейной алгебры (матричный анализ) [23], построение множества (или графа) достижимых состояний, имитационное моделирование [29,30]. С использованием методов линейной алгебры обычно определяются P-инварианты и Т-инварианты. Р-инвариант - это линейное отношение на маркировке подмножества позиций, выражающееся в том, что взвешенная сумма различных меток в позициях является константой и равна значению, определяемому начальной маркировкой. Если в Р-инвариант входят все позиции сетевой модели, то такая сетевая модель является ограниченной. Т-инвариант соответствует последовательности срабатываний переходов, переводящей сеть из маркировки М в ту же самую маркировку М. Если Тинвариант включает все переходы сети, то она жива. При верификации на основе предикатных сетей может использоваться также так называемый метод «структурной индукции». Пусть необходимо проверить свойство Р, например, инвариант. Это свойство проверяется при начальной маркировке, затем допускается, что это свойство верно при произвольной маркировке М, после чего доказывается сохранение этого свойства после срабатывания произвольного перехода. Граф достижимых состояний (ГДС) сетевой модели N есть ориентированный граф GN = (V,E,L), где V - множество вершин, равное множеству достижимых состояний сетевой модели; E ⊆V x V - множество дуг такое, что (si,sj) ∈ E, если состояние sj непосредственно достижимо из состояния si; L:E→T - функция разметки дуг именами переходов такая, что L(si,sj)=t, если состояние sj непосредственно достижимо из состояния si при срабатывании перехода t. Анализ свойств сетевой модели по ГДС дает наиболее полную характеристику ее поведения, поскольку ГДС перечисляет все состояния и все последовательности срабатываний. Свойство живости распознается, например, по наличию последовательностей срабатывания, начинающихся в каждом достижимом (из начального) состоянии и ведущих в начальное состояние. Следует отметить, что некоторые свойства сетевой модели могут быть легко получены на основе визуального анализа ГДС, при этом само графическое представление должно быть небольшим и обозримым для восприятия.
1.3. Представление предикатных сетей на языке Пролог Для представления предикатных сетей используется язык логического программирования Пролог. В общем случае Пролог-программа представляется совокупностью хорновских клозов вида: B :- A1, ..., An, где Ai (i=1, n ) является условием, а В – заключением. Выполнение всех условий А1, ..., Аn влечет заключение В. Все Аi и В являются атомарными формулами, имеющими вид Р(t1,...,tk), где Р – k-арный предикатный символ, а ti (i=1, k ) – терм. Терм может быть переменной, функцией или константой. Хорновский дизъюнкт имеет нуль или более условий и не более одного заключения. Существует четыре различные формы хорновских клозов в свете их процедурной интерпретации: 1) В клозе присутствуют и условия, и заключение: B :- A1, ..., An (n ≥ 1). Этот сорт хорновских клозов интерпретируется как декларация процедуры. Заключение B интерпретируется как имя процедуры, множество условий {A1, ..., An } интерпретируется как тело процедуры; 2) В клозе присутствует только заключение: B :– Этот сорт хорновских клозов интерпретируется как утверждение факта; 3) В клозе присутствуют только условия: :– A1, ..., An (n ≥ 1) Этот сорт хорновских клозов интерпретируется утверждение, представленное в форме отрицания.
как
целевое
Ниже рассматриваются правила кодировки предикатных сетей на языке Пролог. Полученный набор клозов может использоваться для интерпретации сетевой модели. В дальнейшем рассматриваются сетевые модели с позициями, имеющими бесконечную емкость. Предполагаем, что имена элементов сетевой модели совпадают с именами их представлений в Прологпрограмме.
Маркировка предикатной сети представляется списком, состоящим из термов следующего вида: pname(a1, a2, ..., an), где pname – имя маркированной позиции (символьная константа), (a1, a2, ..., an) – кортеж индивидуальностей, представляющий метку, находящуюся в позиции pname, где аi – символьная константа языка Пролог. При использовании расширенных предикатных сетей символ аi может быть термом языка Пролог, включающим только символьные константы или константные термы. Функторы внутренних термов, входящих в рассматриваемый внешний терм, представляющий метку, определяют соответствующие имена подструктур данной метки. Если в позиции pname находится m меток, то число термов с функтором pname в списке должно быть также равно m. Каждый переход сетевой модели представляется клозом следующего вида: arc(S,transition_name,S1):remove(preconditions,S,S2), , insert(postconditions,S2,S1). Предикат arc(S,transition_name,S1) является истинным, если при срабатывании перехода transition_name сетевая модель переходит из маркировки S к маркировке S1. Переход transition_name представляется либо символьной константой tname, либо термом вида: tname(X1, ..., Xf), где tname – имя перехода: Xi (i=1, f ) – переменные, встречающиеся в пометке входных дуг данного перехода. Определение перехода с помощью терма используется для возможности его индексирования. С использованием списка preconditions определяется истинность условий разрешенности перехода, отмеченных выше буквами a и б. Список preconditions состоит из термов следующего вида: pname(X1, X2, ..., Xk), где pname – имя входной позиции перехода transition_name; (X1, X2, ..., Xk) – кортеж из переменных и индивидуальностей, входящий в пометку входной дуги (pname, transition_name) предикатной сети. В расширенных предикатных сетях элемент Xi может быть термом. Следует отметить, что терм с функтором pname встречается в списке preconditions столько раз, сколько кортежей в формальной сумме, помечающей дугу
(pname, transition_name). Если данная дуга отмечена символом ⊄, то соответствующий терм вырождается в символьную константу pname. В списке preconditions должны фигурировать имена всех входных позиций перехода. Язык Пролог имеет мощный встроенный механизм подстановки и конкретизации, что позволяет компактно и элегантно выразить условия разрешенности перехода, отмеченные буквами a и б. Для проверки данных условий разрешенности используется предикат remove. Предикат remove(preconditions,S,S2) является истинным, если имеется такая конкретизация термов в списке preconditions, что при их удалении из маркировки S получается маркировка S2. Предикат remove определяется с помощью следующих клозов: remove([E|X], L2, L3) :– delel(E, L2, LP), remove(X, LP, L3). remove([ ], L, L). Предикат delel используется для удаления элемента из списка. Предикат delel(E, L2, LP) истинен, если элемент Е содержится в списке L2 и при удалении этого элемента из списка L2 получается список LP. Предикат delel определяется следующим образом: delel(X, [X | L], L). delel(X, [Y | L], [Y | L1]) :- delel(X, L, L1). Условия по данным представляют логическую формулу (см. п. 4 определения предикатных сетей), приписанную переходу и выраженную средствами языка Пролог. С помощью данных условий определяется истинность условия разрешенности перехода, отмеченная буквой с. У перехода могут отсутствовать условия по данным. Условия по данным могут использоваться не только для определения условий разрешенности перехода, но и для манипулирования данными, что согласуется с определением предикатных сетей (см. рис. 1.2 ). С использованием списка postconditions определяются метки, добавляемые в выходные позиции перехода при его срабатывании. Список postconditions состоит из термов следующего вида: pname(X1, X2, ..., Xq), где pname – имя выходной позиции перехода transition_name; (X1, X2, ..., Xq ) – кортеж из переменных и индивидуальностей, входящий в пометку выходной дуги (transition_name, pname) предикатной сети. В расширенных предикатных сетях элемент Xi может быть термом. Следует отметить, что терм с функтором pname встречается в списке postconditions столько раз, сколько кортежей в формальной сумме, помечающей дугу (transition_name, pname). Если данная дуга отмечена символом ⊄, то соответствующий терм
вырождается в символьную константу pname. В списке postconditions должны фигурировать имена всех выходных позиций перехода. Добавление меток в выходные позиции перехода осуществляется с помощью предиката insert. Предикат insert(postconditions, S2,S1) является истинным, если имеется такая конкретизация термов в списке postconditions, что при их добавлении к маркировке S2 получается маркировка S1. Предикат insert определяется с помощью следующих клозов: insert([ ], L, L). insert([X | L1], L2, [X | L3]) :- insert(L1, L2, L3). В качестве простого примера рассмотрим кодирование сетевой модели, приведенной на рис. 1.5. Модель состоит из одного перехода, представляемого следующими клозами: init([p1(a), p1(a), p1(b), p1(b), p1(b), p2(b,c), p2(b,b), p4, p4]). arc(S, t1, S1) :– remove([p1(X), p1(X), p2(Y,Z)], S, S2), less(Y,Z), insert([p3(X,Y), p3(X,Z), p4], S2, S1). less(a,b). less(b,c). С помощью предиката init задается начальная маркировка сетевой модели. Предикат less определяет порядок на множестве индивидуальностей {a,b,c}. При целевом утверждении: init(S), arc(S,t1,S1) система выдаст ответ: S = [p1(a), p1(a), p1(b), p1(b), p1(b), p2(b,c), p2(b,b), p4, p4] S1 = [p1(b), p1(b), p1(b), p2(b,b), p3(a,b), p3(a,c), p4, p4, p4]. Полученный результат можно проинтерпретировать следующим образом: сетевая модель при срабатывании перехода t1 перешла из начального состояния S в заключительное состояние S1.
1.4. Построение графа достижимых состояний с помощью языка Пролог В нашем случае для исследования предикатных сетей будем пользоваться методом построения графа достижимых состояний (ГДС). Для реализации данного метода, равно как и для представления предикатных сетей, используется язык логического программирования Пролог. Cледует отметить, что могут быть выделены хорновские клозы, описывающие алгоритмы функционирования PВС и представленные с помощью предикатных сетей; ограничения, налагаемые на функционирование системы; методы исследования, требования к системе,
интерпретация свойств модели. Выделенные группы клозов можно назвать функциональными базами знаний. Каждая подобная база знаний будет использоваться для выполнения определенных функций. Утверждения относительно свойств корректности исследуемой системы можно определить как целевые. Для доказательства целевого утверждения (вернее, для опровержения его невыполнимости) используется метод резолюций [2]. Работа Пролог-интерпретатора является примером символьного выполнения программы. Для построения ГДС используется предикат seq с тремя аргументами, определяемый следующими клозами: seq(S,[T|L],S2):- arc(S,T,S1), rstate(NS,S), inbase(NS,T,S1), seq(S1,L,S2). seq(S,[],S). Предикат seq(S,[T:L],S2) истинен, если последовательность срабатывания переходов из списка [T:L] переводит сетевую модель из маркировки S в маркировку S2. Из первого приведенного выше клоза видно, что это будет в том случае, когда срабатывание перехода Т переводит сетевую модель из маркировки S в маркировку S1 (предикат arc). Маркировка S1 не является дублирующей (предикат inbase), и последовательность срабатывания переходов из списка L переводит сетевую модель из маркировки S1 в маркировку S2 (предикат seq). Предикат rstate с двумя аргументами определяет базу данных о достигнутых маркировках. Структура факта этой базы данных следующая: первый атрибут - номер маркировки, второй атрибут - маркировка, представленная в виде списка. Нумерация маркировок осуществляется в ходе построения ГДС. Текущий номер маркировки находится в базе данных count. Выражение rstate(NS,S) определяет, содержится ли состояние S в базе данных, в которой хранятся все достигнутые состояния. Если состояние S содержится в базе данных, то предикат истинен. При этом переменная NS конкретизируется внутренним номером данного состояния. Предикат inbase с тремя аргументами предназначен для включения информации о новой маркировке и новой дуге ГДС в соответствующие базы данных, а также для определения того, является ли новая маркировка дублирующей. Факты в базе данных о дугах ГДС представляются в виде: gds(NS,T,NS1),
где NS - номер маркировки, представляющей источник дуги; NS1 - номер маркировки, представляющий приемник дуги; Т - переход, срабатывание которого переводит сетевую модель из одной маркировки к другой. Предикат inbase определяется следующим образом: inbase(NS,T,S1):-
rstate(NS1,S1),remove(S,S1,[]),
assert(gds(NS,T,NS1)),!,fail. inbase(NS,T,S1):- retract(count(N)), NS1 is N + 1, assert(count(NS1)), assertz(rstate(NS1,S1)), assertz(gds(NS,T,NS1)). Рассмотрим первый клоз. В нем с помощью предиката remove осуществляется проверка на дублирование полученной маркировки S1. Если маркировки S и S1 равны, то данный предикат истинен. Далее в этом случае с помощью предиката assertz в ГДС включается дуга, ведущая в маркировку S1, делается отсечение и предикат оценивается как ложный. Если маркировки S и S1 не равны, что свидетельствует о том, что получена не дублирующая маркировка S1, то вследствие ложности в этом случае предиката remove из первого клоза Пролог-интерпретатор перейдет к выполнению второго клоза. При этом увеличивается текущий номер маркировок в базе данных count. Полученный номер присваивается новой маркировке S1. Данная маркировка в совокупности с присвоенным номером заносится в базу данных о достигнутых маркировках. В базу данных о дугах ГДС включается информация о дуге, ведущей из маркировки S в маркировку S1. Для печати достигнутых состояний может использоваться предикат writers, определяемый следующим образом: writers:-rstate(N,S),nl,write(N),tab(1),write(S), retract(rstate(N,S)),writers. writers. Для печати ГДС можно воспользоваться предикатом writegds, построенным аналогично предыдущему: writegds:-gds(N1,T,N2),nl,write(N1),tab(1),write(T),tab(1), write(N2),retract(gds(N1,T,N2)),writegds. writegds. Целевой предикат для построения ГДС может иметь следующий вид:
goalgds:- init(S),assertz(rstate(0,S)),assert(count(0)),!, seq(S,_,_),fail. В теле данного клоза производятся некоторые установочные действия, а именно: определяется начальная маркировка S, которая затем включается в базу данных, устанавливается равным нулю текущий номер маркировок. Предикат seq(S,_,_) является рабочим при построении ГДС. Тождественно ложный предикат fail используется для того, чтобы «побудить» предыдущий предикат строить все возможные последовательности срабатывания переходов. Простроенный ГДС может использоваться для определения свойств сетевой модели, причем для определения каждого из свойств могут быть определены соответствующие предикаты.
2. ПРИМЕРЫ МОДЕЛИРОВАНИЯ ВЫЧИСЛИТЕЛЬНЫХ СИСТЕМ И ПРОЦЕССОВ С ИСПОЛЬЗОВАНИЕМ ПРЕДИКАТНЫХ СЕТЕЙ В данной главе рассматриваются следующие примеры моделирования: 1) система с общими ресурсами; 2) задача взаимного исключения; 3) задача "обедающие философы"; 4) алгоритм взаимного исключения в распределенной вычислительной системе; 5) альтернативно-битовый протокол. Для каждого примера изложение будет вестись в следующей последовательности: неформальное описание задачи, сетевое представление задачи с помощью предикатных сетей, результаты исследования сетевой модели на основе построения ГДС.
2.1. Система с общими ресурсами Неформальное описание В качестве первого примера рассмотрим систему из двух параллельных процессов, взаимодействующих путем разделения двух общих ресурсов [25]. В данном случае нас будет интересовать корректность функционирования системы процессов, отсутствие в системе тупиковых ситуаций, что определяется в процессе верификации. Рассматриваемые процессы работают с повторно используемыми ресурсами - R1 и R2 и имеют следующий вид: ПРОЦЕСС 1 --------... Запрос R1 ... M1: Запрос R2 ... Освобождение R2 ... Oсвобождение R1
ПРОЦЕСС 2 --------... Запрос R2 ... M2: Запрос R1 ... Освобождение R1 ... Освобождение R2
Процесс блокируется на примитиве "Запрос", пока не будет распределен ресурс. При выполнении примитива "Освободить" ресурс возвращается в систему. Между примитивами могут располагаться другие операторы. Все операторы, относящиеся к одному процессу, выполняются
последовательно. Если процесс 1 и процесс 2 одновременно достигнут меток М1 и М2 соответственно, то после выполнения примитивов типа "Запрос" оба процесса войдут в тупик. Первый процесс будет блокироваться по R2, сохраняя за собой R1, тогда как второй процесс блокируется по R1, сохраняя R2. Первый процесс не может продолжаться, если не продолжается второй процесс, и наоборот. Процессы сомкнулись в "смертельном объятии". Когда некоторые процессы заблокированы в результате таких запросов на ресурсы, которые никогда не могут быть удовлетворены при отсутствии принятия чрезвычайных системных мер, то о таких процессах говорят, что они зашли в тупик [25]. Сетевая модель Данная задача моделируется с использованием не предикатной сети, а с помощью сети Петри (рис.2.1). Сеть Петри является частным случаем предикатных сетей.
Ðèñ.2.1.Ñåòåâàÿ ìîäåëü ñèñòåìû ñ îáùèìè ðåñóðñàìè Интерпретация позиций сетевой модели следующая: r1 - статус первого ресурса, r2 - статус второго ресурса. Если какая-либо из данных позиций маркирована, то считается, что соответствующий ресурс свободен, если не маркирована - то занят. Остальные позиции определяют состояние соответствующего процесса. Ниже представлена конфигурация переходов и дана их интерпретация. 1. Переход t11 - "Занятие первым процессом первого ресурса". Пре-условия: p11,r1
Пост-условия: p12 2. Переход t12 - "Занятие первым процессом второго ресурса". Пре-условия: p12,r2 Пост-условия: p13 3. Переход t13 - "Освобождение первым процессом обоих ресурсов". Пре-условия: p13 Пост-условия: p11,r1,r2 4. Переход t21 - "Занятие вторым процессом второго ресурса" Пре-условия: p21,r2 Пост-условия: p22 5. Переход t22 - "Занятие вторым процессом первого ресурса" Пре-условия: p22, r1 Пост-условия: p23 6. Переход t23 - "Освобождение вторым процессом обоих ресурсов". Пре-условия: p23 Пост-условия: p21,r1,r2. Переходы данной сетевой модели определяются с помощью следующих клозов: arc(S,t11,S1):-remove([p11,r1],S,S2), insert([p12],S2,S1). arc(S,t12,S1):-remove([p12,r2],S,S2), insert([p13],S2,S1). arc(S,t13,S1):-remove([p13],S,S2), insert([p11,r1,r2],S2,S1). arc(S,t21,S1):-remove([p21,r2],S,S2), insert([p22],S2,S1). arc(S,t22,S1):-remove([p22,r1],S,S2), insert([p23],S2,S1). arc(S,t23,S1):-remove([p23],S,S2), insert([p21,r1,r2],S2,S1). Начальная маркировка сетевой модели определяется следующим фактом: init([p11,p21,r1,r2]). При использовании приведенных в разделе 1.4 клозов будут получены следующие выходные данные, определяющие ГДС: о достигнутых состояниях (база данных rstate): 4 [p22,p11,r1] 2 [p13,p21] 0 [p11,p21,r1,r2] 5 [p23,p11] 3 [p22,p12 1 [p12,p21,r2]
0 t11 1 1 t12 2
о дугах ГДС (база данных gds): 2 t13 0 0 t21 4 4 t22 5 1 t21 3 4 t11 3 5 t23 0
Графическое представление полученного ГДС приведено на рис.2.2. На основе визуального анализа данного ГДС можно сделать вывод, что состояние 3 является тупиковым. Следовательно, сетевая модель не является живой.
Ðèñ.2.2.Ãðàô äîñòèæèìûõ ñîñòîÿíèé ñåòåâîé ìîäåëè ñèñòåìû ñ îáùèìè ðåñóðñàìè.
2.2. Задача взаимного исключения Неформальное описание При работе нескольких параллельных процессов с общими данными возникает необходимость взаимоисключать одновременный доступ процессов к данным. При этом участки программ процессов для работы с разделяемыми данными образуют так называемые критические области (секции). В общем виде постановка задачи взаимного исключения формулируется следующим образом: необходимо согласовать работу n>=2 параллельных процессов при использовании некоторого критического ресурса таким образом, чтобы удовлетворить следующим требованиям [24]: - одновременно внутри критической области должно находиться не более одного процесса; - критические области не должны иметь приоритета в отношении друг друга; - остановка какого-либо процесса вне его критической области не должна влиять на дальнейшую работу процессов по использованию критического ресурса; - решение о вхождении процессов в их критические области при одинаковом времени поступления запросов на такое вхождение и равноприоритетности процессов не откладывается на неопределенное время, а является конечным по времени; - относительные скорости развития процессов неизвестны и произвольны;
- любой процесс может переходить в любое состояние, отличное от активного, вне пределов своей критической области; - освобождение критического ресурса и выход из критической области должны быть произведены процессом, использующим критический ресурс, за конечное время. Задача взаимного исключения является одной из ключевых проблем параллельного программирования. Было предложено много способов решения этой проблемы. Эффективное решение задачи было достигнуто путем использования семафорной техники. Ниже приведено программное решение задачи взаимного исключения с использованием семафоров. PROGRAM взаимоискл.; VAR искл_доступ: SEMAPHORE; ... PROCEDURE процесс_i; BEGIN WHILE истина DO BEGIN ... P(искл_доступ); V(искл_доступ); ... END END; ... BEGIN искл_доступ:=1; PARBEGIN процесс_1; ... процесс_i; ... процесс_N; PAREND END. Семафор "искл-доступ" используется для обеспечения взаимного исключения. Операторы, заключенные между операторными скобками PARBEGIN-PAREND , выполняются параллельно. Сетевая модель
Предикатная сеть, представляющая задачу взаимного исключения для двух процессов, изображена на рис. 2.3. Метка в сетевой модели, соответствующая процессу, имеет один атрибут - индекс (или цвет) процесса из множества {a,b}. Каждому процессу поставлен в соответствие свой индекс.
Рис.2.3.Сетевая модель задачи взаимного исключения Интерпретация позиций сетевой модели следующая: res - двоичный семафор. Данная позиция маркируется меткой без атрибутов (простой меткой). Если позиция res маркирована, то семафор открыт; если же не маркирована, то закрыт. Позиции idle и cr определяют состояния процессов: если позиция idle маркирована меткой с цветом x, то процесс с индексом x находится вне критической области; если позиция cr маркирована меткой с цветом x, то процесс с индексом x находится в своей критической области. Ниже представлена конфигурация переходов сетевой модели и дана их интерпретация. 1. Переход seize(I) - "Закрытие семафора i-м процессом и переход в критическую область". Пре-условия: idle(I),res Пост-условия: cr(I) 2. Переход release(I) - "Открытие семафора i-м процессом и выход из критической области". Пре-условия: cr(I) Пост-условия: idle(I),res.
Переходы данной сетевой модели определяются с помощью следующих клозов: arc(S,seize(I),S1):-remove([idle(I),res],S,S2), insert([cr(I)],S2,S1). arc(S,release(I),S1):-remove([cr(I)],S,S2), insert([idle(I),res],S2,S1). Начальная маркировка сетевой модели определяется фактом: init([idle(a),idle(b),res]). Cледует отметить, что при описании сетевой модели выбраны Прологориентированные обозначения. При этом учитывается тот факт, что переменные в Прологе записываются с большой буквы (например, буква I "И" большая латинская, не путать с единицей). При использовании приведенных в разделе 1.4 клозов будут получены следующие выходные данные, определяющие ГДС: о достигнутых состояниях (база данных rstate): 0 [idle(a),idle(b),res]
1 [cr(a),idle(b)]
2 [cr(b),idle(a)]
о дугах ГДС (база данных gds): 0 seize(a) 1
1 release(a) 0
0 seize(b) 2
2 release(b) 0
Графическое представление полученного ГДС приведено на рис. 2.4 . На основе визуального анализа данного ГДС можно сказать, что соответствующая сетевая модель жива и безопасна, и, следовательно, исходная система параллельных процессов свободна от тупиковых ситуаций.
Рис.2.4.Граф достижимых состояний сетевой модели задачи взаимного исключения Анализ достигнутых маркировок показывает, что в системе отсутствует ситуация, когда два процесса одновременно находятся в своих критических областях.
2.3. Задача "обедающие философы" Неформальное описание Рассмотрим формулировку задачи об обедающих философах в терминологии, предложенной Э. Дейкстрой [23,24]. За круглым столом расставлены пять стульев, на каждом из которых сидит определенный философ(Фi) (рис. 2.5). В центре стола - большое блюдо спагетти, а на столе лежат пять вилок (B1..B5) - каждая между двумя соседними тарелками. Каждый философ может находиться только в двух состояниях - либо он размышляет, либо ест спагетти. Начать думать философу ничто не мешает. Но чтобы начать есть, философу нужны две вилки : одна в правой руке, другая в левой. Закончив еду, философ кладет вилки слева и справа от своей тарелки и опять начинает размышлять до тех пор, пока снова не проголодается.
Рис.2.5.Задача об обедающих философах Существует множество различных формулировок данной задачи, в одной из которых философы интерпретируются как процессы, а вилки как ресурсы. Задача "обедающие философы" удобна для изучения тупиковых ситуаций в системах параллельных процессов. В представленной задаче имеются две опасные ситуации : ситуация голодной смерти и ситуации голодания отдельного философа. Ситуация голодной смерти возникает в случае, когда философы одновременно проголодаются и одновременно попытаются взять, например, свою левую
вилку. В данном случае возникает тупиковая ситуация, так как никто из них не может начать есть, не имея второй вилки. Одним из общих методов избежания тупиков является введение ограничений на число параллельно выполняющихся процессов и ужесточение режима использования ресурсов [25]. Например, тупиковую ситуацию голодной смерти можно избежать, если наложить следующее условие использования вилок - "философу разрешается взять две необходимые для еды вилки в том случае, если они обе свободны". В качестве другого приема, позволяющего избежать данную тупиковую ситуацию, является ограничение числа одновременно сидящих за столом философов (например, до четырех). Для этого, однако, необходимо скорректировать условие задачи и предположить, что стол расположен в столовой, при входе в которую находится швейцар, следящий за числом философов в столовой. Ситуация голодания возникает в случае заговора двух соседей слева и справа против философа, в отношении которого строятся козни. Заговорщики поочередно забирают вилки то слева, то справа от него. Такие согласованные действия злоумышленников приводят жертву к вынужденному голоданию, так как он никогда не может воспользоваться обеими вилками. Сетевая модель Предикатная сеть, представляющая задачу об обедающих философах, изображена на рис. 2.6. Метка в сетевой модели, соответствующая философу, имеет один атрибут - номер философа из множества {1,2,3,4,5}. Каждому философу поставлен в соответствие свой номер. Метка, соответствующая вилке, имеет один атрибут - номер вилки из множества {1,2,3,4,5}. Каждой вилке поставлен в соответствие свой номер.
Рис.2.6.Сетевая модель задачи об обедающих философах Интерпретация позиций сетевой модели следующая: позиция fork определяет свободные в обращении вилки. Позиция think определяет находящихся в размышлении философов. Позиция eat определяет философов, находящихся в состоянии потребления пищи. Ниже представлены переходы сетевой модели и дана их интерпретация и выполняемые действия. Переход get(N) - "Переход N-го философа из состояния размышления в состояние потребления пищи, захват соседних вилок, то есть вилок с номерами N и (N+1)mod5". Переход put(N) - "Переход N-го философа из состояния потребления пищи в состояние размышления, возврат соседних вилок". Переходы сетевой модели описываются следующими клозами: аrc(S,get(N),S1):inlist(think(N),S), mod5(N,NN), remove([think(N),fork(N),fork(NN)],S,S2), insert([eat(N)],S2,S1). arc(S,put(N),S1):inlist(eat(N),S), mod5(N,NN), remove([eat(N)],S,S2), insert([think(N),fork(N),fork(NN)],S2,S1). Следует обратить внимание на представление переходов, несколько отличное от описанного в разделе 1.3. В приведенных клозах перед предикатом remove стоят еще два предиката. Это объясняется тем, что при определении пре-условий необходимо знать закон, по которому связаны
номера N и NN, a именно NN=(N+1)mod5. Сложение по модулю 5 реализуется при помощи предиката mod5 cледующим образом: mod5(X,XX):- X < 5, XX is X + 1, !. mod5(X,XX):- XX is 1. Следует также заметить, что последнее предложение не эквивалентно предложению с анонимной переменной, mod5(_,XX):- XX is 1, поскольку в последнем случае происходит расконкретизация переменной, стоящей на первом месте в списке аргументов предиката mod5. Предикат inlist(E,L) используется для определения принадлежности элемента E списку L и определяется следующим образом: inlist(X,[X|L]). inlist(X,[Y|L]):-inlist(X,L). Начальная маркировка сетевой модели определяется следующим фактом: init([think(1),think(2),think(3),think(4),think(5), fork(1),fork(2),fork(3),fork(4),fork(5)]). Следует отметить, что представленная сеть может моделировать различные ситуации из различных проблемных областей. Ниже представлены выходные данные, определяющие ГДС, полученные с помощью клозов, определенных в разд. 1.4. Достигнутые состояния (база данных rstate): 0 [think(1),think(2),think(3),think(4),think(5),fork(1),fork(2), fork(3),fork(4),fork(5)] 1 [eat(1),think(2),think(3),think(4),think(5),fork(3),fork(4),fork(5)] 2 [eat(3),eat(1),think(2),think(4),think(5),fork(5)] 3 [think(1),fork(1),fork(2),eat(3),think(2),think(4),think(5),fork(5)] 4 [eat(5),think(1),fork(2),eat(3),think(2),think(4)] 5 [think(3),fork(3),fork(4),eat(5),think(1),fork(2),think(2),think(4)] 6 [eat(2),think(3),fork(4),eat(5),think(1),think(4)] 7 [think(5),fork(5),fork(1),eat(2),think(3),fork(4),think(1),think(4)] 8 [eat(4),think(5),fork(1),eat(2),think(3),think(1)] 9 [think(2),fork(2),fork(3),eat(4),think(5),fork(1),think(3),think(1)] 10 [eat(1),think(2),fork(3),eat(4),think(5),think(3)] Дуги ГДС (база данных gds): 0 get(1) 1 1 get(3) 2 2 put(3) 1
5 get(3) 4 5 get(2) 6 6 put(2) 5
9 get(2) 8 9 get(1) 10 10 put(1) 9
1 get(4) 10 1 put(1) 0 0 get(2) 7
2 put(1) 3 3 get(1) 2 3 get(5) 4 4 put(5) 3 4 put(3) 5
6 put(5) 7 7 get(5) 6 7 get(4) 8 8 put(4) 7 8 put(2) 9
10 put(4) 1 9 put(4) 0 7 put(2) 0 5 put(5) 0 3 put(3) 0
0 get(3) 3 0 get(4) 9 0 get(5) 5
На рис. 2.7 полученный ГДС представлен в графическом виде. На основе анализа данного ГДС можно сделать вывод, что соответствующая сетевая модель является живой и, следовательно, исходная система параллельных процессов свободна от тупиков.
Рис.2.7.Граф достижимых состояний сетевой модели задачи об обедающих философах Однако возможна ситуация голодания ("оттеснения") отдельного философа, на что указывают определенные циклы в ГДС. Например, следующий цикл: M9→get(2)→M8→put(4)→M7→get(4)→(M8→get(2)→M9 соответствует оттеснению третьего философа от еды двумя его соседями вторым и четвертым философами. Они создают такую ситуацию, чтобы у третьего философа не было одновременно двух необходимых для еды вилок. В ГДС это соответствует тому, что из маркировок М7, М8, М9,
принадлежащих циклу, нет ни одной выходящей дуги, отмеченной переходом get(3).
2.4. Алгоритм взаимного исключения в распределенной вычислительной системе Неформальное описание Рассматриваемый алгоритм обеспечивает взаимное исключение процессов в РВС, где узлы взаимодействуют только путем обмена сообщениями и не имеют общей разделяемой памяти [34]. Этот алгоритм позволяет проиллюстрировать способность предикатной сети иметь дело с символическими последовательными номерами или временными пометками. Узел РВС входит в критическую секцию только после того, как все другие узлы были оповещены об этом намерении и ими были посланы ответы, подтверждающие их согласие. Узел, делающий попытку войти в критическую секцию, посылает запросное сообщение R всем другим узлам. После приема сообщения R, другой узел или немедленно посылает подтверждение А или откладывает ответ до тех пор, пока он не покинет собственную критическую секцию. Предполагается, что узел, принимающий запрос, может немедленно определить, кто первым войдет в критическую секцию - он сам или запрашивающий узел. Узлу, посылающему запрос, никогда не говорится о причинах выбора того или иного решения, принятого опрашиваемым узлом. В ответ немедленно посылается подтверждение А, если источник запроса имеет приоритет, в других случаях подтверждение откладывается. Определение порядка приоритетов осуществляется путем сравнения номеров временной последовательности, присутствующих в каждом запросе. Если номера данной последовательности равны, то для определения порядка вхождения узлов в критические секции сравниваются их номера. Например, приоритетнее может быть узел, порядковый номер которого больше.
Моделирование времени Приводимая ниже модель алгоритма взаимного исключения интересна в том смысле, что она является примером логико-временной спецификации при помощи логического программирования. Использование в алгоритме взаимного исключения временных пометок поставило следующие
проблемы: 1) Моделирование натуральных чисел, которые представляют временные пометки; 2) Способность задавать эквивалентность между двумя состояниями в различные моменты времени, но имеющих одну и ту же семантику в рамках данной предикатной сети. Модель, пригодная для символического выполнения, представляет натуральные числа при помощи констант, которые могут быть получены при помощи оператора следования. Ниже дается рекурсивное определение натуральных чисел: 1) 0 - натуральное число; 2) Если х - натуральное число, то suc(x) - также натуральное число, где 0 является константой, а "suc" - оператор следования. Модель натуральных чисел используется при моделировании времени. Например, предположим, что в данный момент времени часы показывают 35 единиц времени. Обозначим данный момент времени как h. Следующим значением времени на физических часах будет 36, что представляется как suc(h) и т.д. Интерпретация приведенного выше определения на языке Пролог проста. Мы определяем константу "h" как момент времени в начальном состоянии, и последующие моменты времени моделируются последовательностью suc(h), suc(suc(h)),suc(suc(suc(h))), ... Состояния сетевой модели сохраняют значения всех локальных времен. Значения локальных времен имеют отношение к начальному состоянию (это отношение определено для частных алгоритмов), но локальное время в узле si модифицируется только переходом узла si. Для того, чтобы определить эквивалентность двух состояний в различные моменты времени, но имеющих одинаковую семантику в рамках сетевой модели, рассматривается только отношение между локальными временами. Минимальная модель выводится при поиске минимальной версии каждого достижимого состояния. Состояние находится в своей минимальной версии, если значение локальных часов данного состояния соответствует значению локального времени в начальном состоянии. Чтобы получить минимальную модель, значения часов всех узлов пошагово уменьшаются до тех пор, пока не произойдет возврат к начальному состоянию. Запись shift(s,s1) утверждает, что состояние s1 является минимальной версией состояния s. Предикат shift определяется рекурсивно следующим образом: shift(S,S1):-shiftl(S,S2), shift(S2,S1), !. shift(S,S).
Выражение shiftl(s,s2) утверждает, что состояние s2 непосредственно меньшая версия состояния s, то есть мы уменьшаем значение часов в состоянии s только на единицу времени. Предикат shiftl определяется следующим образом: shiftl([],[]):-!. shiftl([E|S],[E1|S1]):-transfo(E,E1), shiftl(S,S1). Предикат transfo определяет временную трансформацию вида suc(h)→ h для каждой позиции. Например, для позиции poz, предикат определяется следующим фактом: transfo(poz(suc(h)),poz(h)). Применение предиката shift к каждому следующему состоянию достигается путем модификации определения предиката arc: arc(S,transition_name,S1):remove(preconditions,S,S2), , insert(postconditions,S2,S3), shift(S3,S1). Благодаря использованию предиката shift ГДС имеет ограниченное число состояний. Состояния типа I(site_a,suc(suc(...,suc(h)...))), I(site_b,suc(suc(...,suc(h)...))) эквивалентны минимальным состояниям I(site_a,h),I(site_b,h). Сетевая модель Переходы сетевой модели РВС, состоящей из двух узлов, имеют следующую интерпретацию и конфигурацию: 1. Переход: send(I) -"Узел I посылает запрос и ждет подтверждения" Пре-условия: idle(I,H) Пост-условия: request(I,J,suc(H)), waiting(I,suc(H),suc(H)) Условия по данным: others(I,J) 2. Переход: receive(I) - "Узел I посылает подтверждение и входит в критическую секцию" Пре-условия: ack(J,I),waiting(I,O,H) Пост-условия: critical(I,H) Условия по данным: Отсутствуют 3. Переход: release(I) -"Узел I покидает критическую секцию" Пре-условия: critical(I,H) Пост-условия: idle(I,H) Условия по данным: Отсутствуют
4. Переход: i_reply(I) -"Свободный узел I посылает подтверждение" Пре-условия: idle(I,H), request((J,I,O) Пост-условия: ack(I,J), idle(I,K) Условия по данным: others(I,J), max(H,O,K) 5. Переход: w_reply(I) -"Ожидающий узел I посылает подтверждение" Пре-условия: waiting(I,OI,H), request(J,I,Oj) Пост-условия: ack(I,J), waiting(I,OI,K) Условия по данным: others(I,J), max((H,OJ,K), priority(OJ,OI,J,I) Условия по данным определяются с помощью предикатов others, max, priority следующим образом: others(site_a,site_b) - "Узел site_B является соседом узла site_A"; others(site_b,site_a) - "Узел site_A является соседом узла site_B". max(X,X,X) - "Максимум из X и X есть X"; max(X,suc(X),suc(X)) - "Максимум из X и suc(X) есть suc(X)"; max(suc(X),X,suc(X)) - "Максимум из suc(X) и suc(X) есть suc(X)"; priority(X,suc(X),I,J) - "Узел I с локальным временем X имеет приоритет над запрашивающим узлом J c временной пометкой suc(X) "; priority(X,X,I,J):- order(I,J) - "Для определения приоритета двух узлов с равными временными метками используется предопределенный порядок, задаваемый предикатом order"; order(site_a,site_b) - "Приоритет узла site_a выше приоритета узла site_b". Следует обратить внимание на индексацию переходов цветами из множества {site_a,site_b}, что сделано для их выделения из множества переходов с одинаковой семантикой относительно передающего и принимающего узла. Клозы, задающие переходы сетевой модели, имеют следующий вид: arc(S,send(I),S1):remove([idle(I,H)],S,S2), others(I,J), insert([request(I,J,suc(H)),waiting(I,suc(H),suc(H))],S2,S3), shift(S3,S1). arc(S,receive(I),S1):remove([ack(J,I),waiting(I,O,H)],S,S2), insert([critical(I,H)],S2,S3), shift(S3,S1). arc(S,release(I),S1):remove([critical(I,H)],S,S2), insert([idle(I,H)],S2,S3), shift(S3,S1).
arc(S,i_reply(I),S1):remove([idle(I,H),request(J,I,O)],S,S2), others(I,J),max(H,O,K), insert([ack(I,J),idle(I,K)],S2,S3), shift(S3,S1). arc(S,w_reply(I),S1):remove([waiting(I,OI,H),request(J,I,OJ)],S,S2), others(I,J),max(H,OJ,K),priority(OJ,OI,J,I), insert([ack(I,J),waiting(I,OI,K)],S2,S3), shift(S3,S1). Клозы, определяющие временную трансформацию для каждой позиции: transfo(idle(I,suc(H)),idle(I,H)). transfo(request(I,J,suc(H)),request(I,J,H)). transfo(waiting(I,suc(H),suc(H)),waiting(I,H,H)). transfo(ack(I,J),ack(I,J)). transfo(critical(I,suc(H)),critical(I,H)). Графическое представление рассмотренной сетевой модели приведено на рис. 2.8. Начальная маркировка данной сетевой модели определяется следующим фактом: init([idle(site_a,h),idle(site_b,h)]).
Рис.2.8.Сетевая модель алгоритма взаимного исключения При использовании приведенных в разд. 1.4 клозов, будут получены следующие выходные данные, определяющие ГДС: о достигнутых состояниях (база данных rstate): 0 [idle(site_a,h),idle(site_b,h)] 1 [request(site_a,site_b,suc(h)),waiting(site_a,suc(h),suc(h)), idle(site_b,h)] 2 [request(site_b,site_a,h),waiting(site_b,h,h), request(site_a,site_b,h),waiting(site_a,h,h)] 3 [ack(site_b,site_a),waiting(site_b,h,h),request(site_b,site_a,h), waiting(site_a,h,h)] 4 [critical(site_a,h),waiting(site_b,h,h),request(site_b,site_a,h)] 5 [idle(site_a,h),waiting(site_b,h,h),request(site_b,site_a,h)] 6 [request(site_a,site_b,suc(h)),waiting(site_a,suc(h),suc(h)), waiting(site_b,h,h),request(site_b,site_a,h)] 7 [ack(site_a,site_b),waiting(site_a,suc(h),suc(h)), request(site_a,site_b,suc(h)),waiting(site_b,h,h)]
8 [critical(site_b,h),waiting(site_a,suc(h),suc(h)), request(site_a,site_b,suc(h))] 9 [ack(site_a,site_b),idle(site_a,h),waiting(site_b,h,h)] 10 [critical(site_b,h),idle(site_a,h)] 11 [ack(site_b,site_a),idle(site_b,h),waiting(site_a,h,h)] 12 [request(site_b,site_a,suc(h)),waiting(site_b,suc(h),suc(h)), ack(site_b,site_a),waiting(site_a,h,h)] 13 [critical(site_a,h),request(site_b,site_a,suc(h)), waiting(site_b,suc(h),suc(h))] 14 [idle(site_a,h),request(site_b,site_a,suc(h)), waiting(site_b,suc(h),suc(h))] 15 [critical(site_a,h),idle(site_b,h)] о дугах ГДС (база данных gds): 0 send(site_a) 1 1 send(site_b) 2 2 w_reply(site_b) 3 3 receive(site_a) 4 4 release(site_a) 5 5 send(site_a) 6 6 w_reply(site_a) 7 7 receive(site_b) 8
8 release(site_b) 1 5 i_reply(site_a) 9 9 send(site_a) 7 9 receive(site_b) 10 10 send(site_a) 8 10 release(site_b) 0 1 i_reply(site_b) 11 11 send(site_b) 12
12 receive(site_a) 13 13 release(site_a) 14 14 send(site_a) 2 14 i_reply(site_a) 9 11 receive(site_a) 15 15 send(site_b) 13 15 release(site_a) 0 0 send(site_b) 14
Графическое представление данного ГДС приведено на рис. 2.9. После того, как конечно-автоматная модель, представленная графом достижимых состояний, построена, проверяются три фундаментальные свойства рассматриваемого алгоритма взаимного исключения: - взаимное исключение; - отсутствие оттеснений (умираний); - отсутствие тупиков.
Рис.2.9.Граф достижимости состояний сетевой модели алгоритма взаимного исключения Следует заметить, что проверка данных свойств на основе визуального анализа затруднена и данные свойства неочевидны. В подразделе 3.3 будет проведена проверка данных свойств с использованием временной логики.
2.5. Альтернативно-битовый протокол Неформальное описание В качестве примера протокола для исследования выбран простой протокол "с нумерацией по модулю 2", хорошо известный также под названием альтернативно-битового протокола (АБ-протокола) [26,27]. В соответствии с моделью ВОС АБ-протокол относится к канальному уровню. Модель уровня АБ-протокола представлена на рис.2.10. Канальные сервисные блоки данных в дальнейшем будем называть кадрами, а сетевые сервисные блоки данных - сообщениями. Синтаксис АБ-протокола несложен и представляет собой определение форматов кадров для данных и подтверждений. В поле управления кадра имеется бит четности кадра, принимающий значение 0 или 1. Для кадра данных обозначим его через FP, а для кадра подтверждения - через АР. Значения бита четности в последовательно передаваемых кадрах данных чередуются. После того как по логическому каналу передан кадр данных с битом четности 0, следующий кадр данных по этому же каналу будет передаваться с битом четности 1, но только после того, как принято подтверждение о принятии предыдущего кадра. Пользователи верхнего (сетевого) уровня обмениваются с уровнем АБпротокола сообщениями, а среда (физический уровень) передает кадры. Среда может задерживать, искажать и терять кадры, но не может их переупорядочивать и дублировать. Среда обеспечивает двунаправленную
передачу кадров. На рис.2.10 через X и Y обозначены точки доступа к сервису, предоставляемому АБ-протоколом, а α, β, γ, δ - точки доступа к сервису, используемому АБ-протоколом. Примитивы ПРД, ПРН, "передать", "принять" играют только синхронизирующую роль, поэтому информация должна помещаться в точки доступа и извлекаться из них явным способом. Примитивы ПРД и ПРН могут выполняться только совместно с объектом верхнего уровня, а "передать" и "принять" - совместно со средой.
Рис.2.10.Модель уровня альтернативно-битового протокола В структуру объекта-передатчика входят : буфер для переданного, но не подтвержденного кадра, таймер (часы) для реализации механизма таймаутов, бит-переменная ТР - четность передатчика (рис.2.10). В структуру объекта-приемника входит переменная RP - четность приемника, используемая для контроля правильности последовательности битов четности кадров. Семантика АБ-протокола состоит в действиях по передаче и приему кадров. Определим семантику АБ-протокола в форме словесного описания.
Получив требуемое для передачи сообщение, объект-передатчик формирует из него кадр данных и устанавливает бит четности кадра, равный четности передатчика. Сформированный таким образом кадр передается в среду, а его копия сохраняется в буфере передатчика. После этого передатчик дожидается поступления кадра подтверждения, содержащего бит четности, значение которого равно значению четности последнего переданного кадра данных. Если кадр подтверждения принимается с искажениями или бит четности в подтверждении не сов падает со значением бита четности последнего переданного кадра данных, то передатчик повторно передает запоминаемую копию. Иначе останавливается таймер, освобождается буфер, значение бита четности меняется на противоположное. Если таймер выдал сигнал окончания тайм-аута, то передатчик повторно передает помещенную в буфер передатчика копию кадра. Окончание таймаута свидетельствует (если исключить из рассмотрения сбои аппаратуры) о потере или кадра данных, или кадра подтверждения. При потере кадра подтверждения при повторной передаче кадра данных произойдет нарушение правильности последовательности битов четности, что обнаружится приемником, и дублирующий кадр будет отброшен. Объект-приемник, приняв кадр, проверяет, не искажен ли кадр средой. Если кадр искажен или значение бита четности принятого кадра данных не равно значению бита четности приемника, то приемник уничтожает принятый кадр, в противном случае он выделяет из кадра сообщение и передает его пользователю-получателю. В любом случае приемник формирует кадр подтверждения, значение бита четности в котором устанавливает равным значению бита последнего принятого кадра. Заметим, что первоначальные значения четности приемника и четности передатчика устанавливаются равными друг другу. В литературе [26,27] описывается АБ-протокол, в котором первоначальные значения четности передатчика и приемника не совпадают, что в конечном счете не принципиально. Следует отметить, что для формального описания семантики АБпротокола применимы все средства и методы формального описания, перечисленные в начале данной главы. Каждый из методов имеет свои преимущества и недостатки. Предпочтение тому или иному методу может быть отдано в зависимости от целей дальнейшего использования формального описания: для верификации, оценки качества функционирования протокола и выбора параметров протокола или для реализации. В [26] АБ-протокол описан с использованием диаграмм состояний и в виде программы, в [33] - с использованием сети "предикатпереход", в [27] - с использованием временной логики, языков LOTOS,ESTELLE и OCA.
Формально семантика АБ-протокола может описываться в виде программы, приведенной ниже. ПЕРЕДАТЧИК Посылка нового кадра ЕСЛИ TS = "готова", ТО {TS:= "занята"; Выбрать кадр со входа передатчика и поместить в буфер; FP:=TP; Передать кадр; Запустить таймер;} Прием подтверждения ЕСЛИ нет ошибок и AP=TP, TO {Удалить кадр из буфера; Остановить таймер; TP:=(TP+1)mod2; TS:= "готова"; } ИНАЧЕ Повторная передача;
ПРИЕМНИК Прием кадра ЕСЛИ нет ошибок и FP=RP, ТО { Передать принятый кадр на верхний уровень; RP:=(FP+1)mod2; } AP:=FP; Послать подтверждение;
Окончание тайм-аута Повторная передача; Повторная передача FP:=TP; Передать кадр; Повторный запуск таймера;
Здесь приняты следующие обозначения: RP - четность приемника; TP четность передатчика; FP - четность кадра; AP - четность подтверждения; TS - состояние передатчика. Начальные условия системы: RP=TP; TS="готова". Сетевая модель Для целей верификации АБ-протокол удобно представить в виде предикатной сети (рис.2.11). Следует отметить, что в представленной модели считается, что любое искажение кадра распознаваемо и не приводит к появлению действительных кадров. В сетевой модели не рассматриваются следующие ситуации: 1) прием подтверждения, четность которого не равна четности посланного кадра; 2) прием искаженного подтверждения (данная ситуация моделируется ситуацией потери подтверждения). На принятом уровне абстракции не рассматривается явно работа таймера.
Ðèñ.2.11.Ñåòåâàÿ ìîäåëü àëüòåðíàòèâíî-áèòîâîãî ïðîòîêîëà Существует три типа меток, циркулирующих в рассматриваемой сетевой модели: 1) метки, циркулирующие по позициям, определяющим состояние передатчика (psend и wait) и приемника (prec); 2) метки, циркулирующие по позициям, представляющим тракт передачи (send, receive); 3) метки, представляющие признаки. Метки первого типа имеют один атрибут - четность (0 или 1). Метки второго типа имеют следующую структуру: 1-й атрибут - идентификатор (адрес) передающей стороны; 2-й атрибут - идентификатор (адрес) принимающей стороны; 3-й атрибут - тип сообщения; 4-й атрибут - четность сообщения. Домен идентификаторов передающей или принимающей стороны множество {se,re}, причем se соответствует передатчику, а re -приемнику. Следует заметить, что как приемник, так и передатчик могут выполнять роль как приемной, так и передающей сторон. Кадр в АБ- протоколе может быть двух типов: информационным кадром (кодируется как mes) и подтверждением (кодируется как ack). Четность кадра может принимать значение zero (ноль) или one (единица). Вместо zero и one иногда будем писать 1 и 0 соответственно. Метки третьего типа не имеют атрибутов. Интерпретация позиций сетевой модели следующая (интерпретация приводится для маркированных позиций):
psend - готовность передатчика послать новый кадр. Четность передатчика определяется атрибутом находящейся в данной позиции метки; wait - ожидание приема подтверждения; send - посылка передатчиком кадра; receive - прием кадра приемником; prec - готовность приемника принять кадр. Четность приемника определяется атрибутом находящейся в данной позиции метки. Ниже представлена конфигурация переходов сетевой модели и дана их интерпретация. 1. Переход tsend(B) - "Посылка передатчиком нового кадра и переход из состояния готовности в состояние ожидания подтверждения". Пре-условия: psend(B). Пост-условия: wait(B), send(se,re,mes,B). 2. Переход recack(B) - "Прием подтверждения передатчиком, переход из состояния ожидания в состояние готовности, изменение четности передатчика". Пре-условия: wait(B),receive(re,se,ack,B). Пост-условия: psend(BB). Преобразования в переходе: comp(B,BB). 3. Переход repeatm(B) - "Повторная передача кадра". Пре-условия: wait(B), ploss. Пост-условия: wait(B), send(se,re,mes,B). 4. Переход propagate(M) - "Передача сообщения по каналу передачи". Пре-условия: send(X,Y,T,M). Пост-условия: receive (X,Y,T,M). 5. Переход loss - "Потеря сообщения". Пре-условия: send(X,Y,T,M). Пост-условия: ploss. 6. Переход reception(B) - "Принять кадр и изменить четность приемника". Пре-условия: receive(X,re,mes,B), prec(B). Пост-условия: prec(BB), send(re,X,ack,B). Преобразования в переходе: comp(B,BB). 7. Переход repeata(B) - "Повторная передача подтверждения". Пре-условия: receive(X,re,mes,BB), prec(B). Пост-условия: prec(B), send(re,X,ack,BB). Условия по данным: comp(B,BB). Предикат comp определяется с помощью фактов следующим образом: comp(zero,one). comp(one,zero).
Cледует заметить, что утверждение comp(B,BB) используется как условие в случае, когда обе переменные B и BB конкретизированы, так и для реализации операции "сложение по модулю 2", в этом случае BB=B ⊕1. Клозы, определяющие переходы данной сетевой модели, имеют следующий вид: arc(S,tsend(B),S1):remove([psend(B)],S,S2), insert([send(se,re,mes,B),wait(B)],S2,S1). arc(S,loss,S1):remove([send(X,Y,T,M)],S,S2), insert([ploss],S2,S1). arc(S,propagate(M),S1):remove([send(X,Y,T,M)],S,S2), insert([receive(X,Y,T,M)],S2,S1). arc(S,recack(B),S1):remove([receive(re,se,ack,B),wait(B)],S,S2), comp(B,BB), insert([psend(BB)],S2,S1). arc(S,repeatm(B),S1):remove([wait(B),ploss],S,S2), insert([wait(B),send(se,re,mes,B)],S2,S1). arc(S,repeata(B),S1):remove([receive(X,re,mes,BB),prec(B)],S,S2), comp(B,BB), insert([prec(B),send(re,X,ack,BB)],S2,S1). arc(S,reception(B),S1):remove([receive(X,re,mes,B),prec(B)],S,S2), comp(B,BB), insert([prec(BB),send(re,X,ack,B)],S2,S1). Начальная маркировка сетевой модели определяется следующим фактом: init([psend(zero),prec(zero)]). При использовании приведенных в разд. 1.4 клозов получаются следующие выходные данные, определяющие ГДС: о достигнутых состояниях (база данных rstate): 0 [psend(zero),prec(zero)] 1 [send(se,re,mes,zero),wait(zero),prec(zero)] 2 [ploss,wait(zero),prec(zero)] 3 [receive(se,re,mes,zero),wait(zero),prec(zero)] 4 [prec(one),send(re,se,ack,zero),wait(zero)] 5 [ploss,prec(one),wait(zero)]
6 [wait(zero),send(se,re,mes,zero),prec(one)] 7 [receive(se,re,mes,zero),wait(zero),prec(one)] 8 [receive(re,se,ack,zero),prec(one),wait(zero)] 9 [psend(one),prec(one)] 10 [send(se,re,mes,one),wait(one),prec(one)] 11 [ploss,wait(one),prec(one)] 12 [receive(se,re,mes,one),wait(one),prec(one)] 13 [prec(zero),send(re,se,ack,one),wait(one)] 14 [ploss,prec(zero),wait(one)] 15 [wait(one),send(se,re,mes,one),prec(zero)] 16 [receive(se,re,mes,one),wait(one),prec(zero)] 17 [receive(re,se,ack,one),prec(zero),wait(one)] о дугах ГДС (база данных gds): 0 tsend(zero) 1 1 loss 2 2 repeatm(zero) 1 1 propagate(zero) 3 3 reception(zero) 4 4 loss 5 14 repeatm(one) 15 15 loss 14
5 repeatm(zero) 6 6 loss 5 6 propagate(zero) 7 7 repeata(one) 4 4 propagate(zero) 8 8 recack(zero) 9 15 propagate(one) 16 16 repeata(zero) 13
9 tsend(one) 10 10 loss 11 11 repeatm(one) 10 10 propagate(one) 12 12 reception(one) 13 13 loss 14 13 propagate(one) 17 17 recack(one) 0
На рис.2.12 полученный ГДС представлен в графическом виде. На основе анализа данного ГДС можно сделать вывод, что соответствующая сетевая модель является живой, и, следовательно, АБ- протокол свободен от тупиков.
Ðèñ.2.12.Ãðàô äîñòèæèìûõ ñîñòîÿíèé ñåòåâîé ìîäåëè àëüòåðíàòèâíî-áèòîâîãî ïðîòîêîëà Типичным примером Р- инварианта является выражение: М(psend) + M(wait) = 1, определяющее то, что передатчик находится либо в состоянии psend, либо в состоянии wait (исключительно). В полученном ГДС можно выделить следующие последовательности переходов: 1) (0)→tsend(zero), propagate(zero), reception(zero), propagate(zero), recack(zero)→(9). Данная последовательность соответствует нормальной передаче кадра с четностью 0. 2) (9)→tsend(one), propagate(one), reception(one), propagate(one), recack(one)→0. Данная последовательность соответствует нормальной передаче кадра с четностью 1. 3) (4)→loss, repeatm(zero), propagate(zero), repeata(zero)→(4).
Данная последовательность соответствует потере подтверждения с четностью 0 и восстановлению после этой ошибки. 4) (13)→loss, repeatm(zero), propagate(zero), repeata(zero)→(13). Данная последовательность соответствует потере подтверждения с четностью 1 и восстановлению после этой ошибки. 5) (1)→loss, repeatm(zero)→(1) и (6)→loss, repeatm(zero)→(6). Данные последовательности соответствуют потере кадра с четностью 0 и восстановлению после этой ошибки. 6) (10)→loss, repeatm(zero)→(11) и (15)→loss, repeatm(zero)→(14). Данные последовательности соответствуют потере кадра с четностью 1 и восстановлению после этой ошибки.
3. ВЕРИФИКАЦИЯ ВЫЧИСЛИТЕЛЬНЫХ СИСТЕМ И ПРОЦЕССОВ С ИСПОЛЬЗОВАНИЕМ ВРЕМЕННОЙ ЛОГИКИ, ИНТЕРПРЕТИРУЕМОЙ НА ЯЗЫКЕ ПРОЛОГ Ниже рассматривается процесс верификации и возможности использования при этом языка Пролог. Язык Пролог имеет встроенный мощный механизм логического вывода, что делает его привлекательным для решения логических задач. Под верификацией понимается проверка корректности и правильности логического поведения системы. Считается, что система функционирует корректно, если ее поведение отвечает ряду априори сформулированных требований, причем существуют как общие, так и частные требования. Общие требования относятся ко всем альтернативным вариантам систем заданного класса. Частные требования относятся к конкретной системе и отражают специфические детали ее функционирования. По отношению к коммуникационным протоколам могут быть названы следующие общие требования: отсутствие тупиков, полнота, отсутствие бесполезных зацикливаний, недопустимость переполнения, соответствие терминальных состояний поставленным в спецификациях целям. При верификации системы могут использоваться как математические, так и имитационные модели. В соответствии с модельным подходом технологическая цепочка исследования системы будет следующей: [Исследуемая система] → (Формализованное описание) → [Модель системы] →(Исследование модели) → [Свойства модели] →(Интерпретация свойств модели) → [Свойства системы] → (Проверка соответствия свойств системы и предъявляемых к ней требованиям) → [Заключение о корректности функционирования системы]. Здесь в квадратных скобках записаны начальные, промежуточные и конечные результаты технологической цепочки, а в круглых – совершаемые действия. При использовании метода имитационного моделирования этап «Исследование модели» может быть детализирован в виде следующей цепочки: (Моделирование) → [Результаты моделирования] → (Анализ результатов моделирования и вычленение свойств модели). Для более целенаправленных действий при верификации с использованием математических моделей может использоваться следующая цепочка: [Исследуемая система] → (Формализованное описание системы и предъявляемых к ней требований) → [Модель системы и выраженные в терминах модели требования] → (Доказательство требуемых свойств системы) → [Заключение о корректности функционирования системы]. В данной главе будет рассматриваться именно эта цепочка, а также
интерпретация пропозициональной ветвящейся временной логики в терминах логического программирования. Здесь же приводится трансформация основных операторов пропозициональной ветвящейся временной логики, называемой логикой дерева вычислений (Computation Tree Logic, сокращенно CTL), в множество клозов языка Пролог [34]. Временная логика может быть основой метода верификации вычислительных систем и процессов, если их можно представить в терминах конечноавтоматной модели. Суть метода заключается в следующем. С использованием спецификации системы составляются формулы временной логики, представляющие определенные утверждения о ее функционировании, которые необходимо доказать. Эти формулы переводятся в прологовские клозы, которые интерпретируются на ЭВМ. При интерпретации используется конечноавтоматная модель функционирования системы, полученная каким-либо образом из ее спецификации.
3.1. Логика дерева вычислений Рассмотрим формальное определение логики дерева вычислений (ЛДВ). Структура ЛДВ- модели есть тройка M=(S,R,P), где S – конечное множество состояний; R ⊆ S × S – бинарное отношение на множестве S, определяющее переходы между состояниями (si,sj) ∈R, если существует переход из состояния si в состояние sj; P – функция назначения состояниям атомарных высказываний. Под атомарным высказыванием понимается высказывание пропозициональной логики. Определим множество ЛДВ-формул. Пусть Pa - множество атомарных высказываний, а Р - множество ЛДВ-формул. Множество Р определяется следующим образом: 1. Ра есть подмножество Р; 2. Если р1∈ Р, то ∼ р1 ∈ Р; 3. Если р1,р2 ∈ Р, то p1&p2 ∈ P, ALL(p1,p2)∈ P, SOME(p1,p2) ∈ P, POT(p1,p2) ∈ P, INEV(p1,p2) ∈ P, где ALL, SOME, POT, INEV - временные операторы. Временные операторы POT и INEV введены для упрощения временных логических выражений. Они могут быть получены из операторов ALL и SOME с использованием следующих соотношений: POT(p1,p2), если ~ALL(p1,~p2);
INEV(p1,p2), если ~SOME(p1,~p2). В дальнейшем для реализации вышеупомянутых четырех временных операторов вводятся два вспомогательных оператора - PRE и PRETILDA. Путь вычислений - это бесконечная последовательность состояний (s0,s1,s2,...), где ∀i (si,si+1) ∈ R. Запись M, s ╞ f или сокращенно s ╞ f означает, что формула f выполнима в состоянии s структуры М. Отношение ╞ определяется следующим образом (в определении p1 и р2 - формулы ЛДВ): 1. s ╞ p, если атомарное высказывание р истинно в состоянии s; 2. s ╞ ~p, если ~(s ╞ p); 3. s ╞ p1&p2, если s ╞ p1 & s ╞ p2; 4.s0 ╞ ALL(p1,p2), если для каждого пути (s0,s1,...,sk) выполняется следующее условие: ∀ i ((0 ≤ i ≤ k) & ∀ j ((0 ≤ j < i) → sj ╞ p1)) → si ╞ p2. Иными словами, ALL(p1,p2) истинно в узле s0 дерева Т, если для каждого пути Т, начинающегося из узла s0, p2 остается истинным, пока р1 не станет ложным; 5. s0 ╞ SOME(p1,p2), если существует путь (s0,s1,...,sk) такой, что ∀ i ((0 ≤ i ≤ k) & ∀ j ((0 ≤ j < i) → sj ╞ p1)) → si ╞ p. Иными словами, SOME(p1,p2) истинно в узле s0 дерева Т, если существует путь в дереве Т, начинающийся из узла s0, и для данного пути р2 остается истинным, пока р1 не станет ложным; 6. s0 ╞ POT(p1,p2), если существует путь (s0,s1,...,sk) такой, что ∃ i ((0 ≤ i ≤ k) & ∀ j ((0 ≤ j < i) → sj ╞ p1)) & si ╞ p2. Иными словами, POT(p1,p2) истинно в узле s0 дерева Т, если существует путь, начинающийся из узла s0 и оканчивающийся в узле si, в котором р1 остается истинным до узла si, и р2 истинно в узле si; 7. s0 ╞ INEV(p1,p2), ecли для каждого пути (s0,s1,...,si,...,sk) выполняется следующее условие: ∃ i ((0 ≤ i ≤ k) & ∀ j ((0 ≤ j < i) → sj ╞ p1)) & si ╞ p2. Иными словами, INEV(p1,p2) истинно в узле s0 дерева Т, если для каждого пути, начинающегося из узла s0 и оканчивающегося в узле si, р1 остается истинным до узла si , и р2 истинно в узле si; 8. s ╞ PRE (p), если ∃ s' (s,s') ∈ R & s'╞ p. Иными словами, PRE(p) в узле s дерева Т истинно, если существует преемник узла s, где р истинно; 9. s ╞ PRETILDA (p), если ∀ s' (s,s') ∈ R → s'╞ p. Иными словами, PRETILDA(p) в узле s дерева Т истинно, если для каждого преемника узла s p истинно.
При вычислении формулы с вложенными временными операторами необходимо определять состояния, на которых будут применяться более "глубокие" операторы. Рассмотрим вычисление формулы s ╞ OP1(OP2(p1,p2),OP3(p3,p4)). Оператор OP1 будет оцениваться на состоянии s, в то время как операторы OP2 и OP3 будут оцениваться на состояниях, определенных при оценке OP1. Аналогично, р1 и р2, а также р3 и р4 будут оцениваться на состояниях, определенных при вычислении OP2 и OP3 соответственно. Формула р выполнима в структуре М, если существует такое состояние s этой структуры, что М,s ╞ p. Формула р общезначима для структуры М, если для каждого состояния s структуры М действительно М,s╞ p. Формула р является теоремой, если она действительна для каждой модели М.
3.2. Интерпретация временной логики на языке Пролог Оценка временных логических операторов основывается на их рекурсивном вычислении с использованием языка Пролог. В данном учебном пособии для этих целей используется версия Пролога - Arity Prolog, используемая IBM-совместимых ПЭВМ [22].
3.2.1. Реализация POT - оператора Реализация уравнением:
этого
оператора
задается
следующим
рекурсивным
T,s ╞ POT(p1,p2), если T,s ╞ p2 ∨ (p1 & PRE POT(p1,p2)) (3.3) Каждая ЛДВ-формула определяет предикат Пролога. Формула s ╞ PRE p представляется предикатом pre(p,l,s), где р - ЛДВ-формула, s - состояние и l - список состояний. Роль списка состояний объясняется ниже. Отношение R представляется предикатом arc, причем arc(s,t,s1) определяет, что переход t изменяет состояние с s на s1. Для оценки формулы s ╞ p используется предикат call. Прологовская интерпретация формулы 3.1 определяется как pre(P,L,S):-arc(S,T,S1), P=..K, insert(K,[L,S1],P0),
P01=..P0, call(P01),!. Оператор отсечения "!" обязывает интерпретатор Пролога искать только первое решение, если оно существует. Рассмотрим реализацию уравнения 3.3, касающегося оператора POT. Представим данное уравнение в следующей форме: T,s ╞ POT(p1,p2), если T,s ╞ p2
(3.4)
T,s ╞ POT(p1,p2), если T,s ╞ p1 & PRE POST(p1,p2)
(3.5)
Прологовская реализация уравнения 3.4: pot(P1,P2,L,S):-P2=..T,insert(T,[S],P0),P01=..P0,call(P01),!. (3.6) Прологовская реализация уравнения 3.5: pot(P1,P2,L,S):-P1=..T,insert(T,[S],P0),P01=..P0,call(P01), pre(pot(P1,P2),[S|L],S).
(3.7)
Хотя прологовские клозы 3.6 и 3.7 эквивалентны уравнениям 3.4 и 3.5, их выполнение на практике не приносит ожидаемых результатов. При их выполнении происходит зацикливание, поскольку невозможно определить, было некоторое состояние пройдено или нет. Без ограничений теоретической модели для избежания зацикливаний вводятся некоторые ограничивающие условия при оценке временных операторов. Эти условия используют список состояний l, введенный выше. Список l строится в ходе оценки данного временного оператора и содержит уже пройденные состояния. Данные условия реализуются с помощью предиката outl. Предикат outl(s,l) истинен, если s не является элементом списка l. Прологовское определение предиката outl следующее: outl(S,[]):-!. outl(S,[S1|L]):-noneg(S,S1), outl(S,L). где noneg(S,S1) - предикат, утверждающий, что S не равно S1. noneg(S,S1):-remove(S,S1,[]),!,fail. noneg(S,S1). Если тот же самый предикат pot(p1,p2) оценивается в том же самом узле s, то ответ должен быть отрицательным. Это условие предотвращает бесконечное зацикливание. С учетом ограничивающего условия POTоператор определяется следующими прологовскими клозами:
pot(P1,P2,L,S):-outl(S,L), P2=..T,insert(T,[S],P0),P01=..P0,call(P01), !. pot(P1,P2,L,S):-outl(S,L), P1=..T,insert(T,[S],P0),P01=..P0,call(P01), pre(pot(P1,P2),[S|L],S).
3.2.2. Реализация ALL-оператора Реализация уравнением:
ALL-оператора
задается
следующим
рекурсивным
T,s ╞ ALL(p1,p2), если T,s ╞ p2 & (~p1 ∨ PRETILDA ALL(p1,p2)) (3.8) Формальное определение оператора PRETILDA задано формулой 3.2. Прямая реализация этой формулы на языке Пролог невозможна из-за наличия квантора всеобщности.Для трансформации формулы 3.2 в эквивалентную, не содержащую квантор всеобщности, воспользуемся известным соотношением: ∀x p(x) ↔ ∼ ∃ x ∼p(x) В результате получается формула: s ╞ PRETILDA p, если ∼∃s' ∼ ((s,s') ∈R → s'╞ p) Заменяя операцию импликации в данной формуле, получаем формулу: s ╞ PRETILDA p , если ~∃s'(s,s') ∈R & ∼(s'╞ p). Эта формула может быть напрямую реализована путем расщепления ее на две части: S ╞ PRETILDA p ← ∼ CPRETILDA(p,s) CPRETILDA(p,s) означает : ∃ s'(s,s') ∈ R & ∼ (s'╞ p) Прологовская интерпретация этих двух выражений следующая: pretilda(P,L,S):-non(cpretilda(P,L,S)). cpretilda(P,L,S):-arc(S,T,S1), P=..K,insert(K,[L,S1],P0),P01=..P0,
non(P01). где non-предикат определяется как non(P):-call(P),!,fail. non(P). Уравнение 3.8 трансформируется в клаузальную представляется в форме следующих прологовских клозов:
форму
и
all(P1,P2,L,S):- P2=..T,insert(T,[S],P0),P02=..P0,call(P02), P1=..K,insert(K,[S],P00),P01=..P00,non(P01), !. all(P1,P2,L,S):-P2=..T,insert(T,[S],P0),P02=..P0,call(P02), pretilda(all(P1,P2),[S|L],S). Однако оценка рекурсивного уравнения 3.8 с помощью данных клозов невозможна ввиду отсутствия ограничивающих условий. Если при попытке оценить предикат all(p1,p2) осуществляется повторный переход в ранее рассмотренное состояние s, то данный предикат необходимо оценить как истинный и прекратить дальнейшую рекурсивную оценку для предотвращения зацикливания. Для определения того, является ли объект элементом списка, вводится предикат inl. Выражение inl(s,l) означает, что s является элементом списка l. Прологовское определение предиката inl следующее: inl(X,[Z|Y]):-remove(X,Z,[]),!. inl(X,[Z|Y]):-inl(X,Y). Используя предикат inl мы можем определить подходящее ограничивающее условие и дать окончательное прологовское определение ALL-оператора: all(P1,P2,L,S):-inl(S,L), !. all(P1,P2,L,S):- P2=..T,insert(T,[S],P0),P02=..P0,call(P02), P1=..K,insert(K,[S],P00),P01=..P00,non(P01), !. all(P1,P2,L,S):-P2=..T,insert(T,[S],P0),P02=..P0,call(P02), pretilda(all(P1,P2),[S|L],S).
3.2.3. Реализация других временных операторов Рекурсивные уравнения для операторов INEV и SOME имеют следующий вид: T,s ╞ INEV(p1,p2), если T,s ╞ p2 ∨ (p1 & PRETILDA INEV(p1,p2)). T,s ╞ SOME(p1,p2), если T,s ╞ p2 & (∼p1 ∨ PRE SOME(p1,p2)). Ниже приводится прологовская реализация данных операторов, включая ограничительные условия: inev(P1,P2,L,S):-inl(S,L),!,fail. inev(P1,P2,L,S):-P2=..K,insert(K,[S],P00),P02=..P00,call(P02), !. inev(P1,P2,L,S):-arc(S,T,S1), !, P1=..K,insert(K,[S],P0),P01=..P0,call(P01), pretilda(inev(P1,P2),[S|L],S). some(P1,P2,L,S):-inl(S,L), !. some(P1,P2,L,S):-P2=..K,insert(K,[S],P0),P02=..P0,call(P02), non(arc(S,T,S1)), !. some(P1,P2,L,S):-P2=..K,insert(K,[S],P00),P02=..P00,call(P02), P1=..T,insert(T,[S],P0),P01=..P0, non(P01), !. some(P1,P2,L,S):-P2=..K,insert(K,[S],P0),P02=..P0,call(P02), pre(some(P1,P2),[S|L],S).
Некоторые упрощения Ниже приводятся некоторые упрощения представления операторов временной логики. Во-первых, список l используется только в ходе
выполнения программы. Таким образом, временной оператор может вызываться без использования этого параметра. В случае POT-оператора, это упрощение определяется следующим клозом: pot(P1,P2,S):-pot(P1,P2,[],S).
Заметим, что начальное значение списка l есть [], что является признаком пустого списка. Дальнейшие упрощения достигаются путем устранения условного предиката р1. В этом случае мы предполагаем, что предикат р1 имеет значение "истина" в некотором состоянии. Декларация этого факта дается следующим прологовским клозом: true(S). Безусловный POT-оператор имеет только два аргумента. Сокращение аргументов POT-оператора может быть задано следующим клозом: pot(P,S):-pot(true,P,[],S). Подобные упрощения могут применяться ко всем другим временным операторам. 3.2.4. Реализация невременных логических операторов При интерпретации ЛДВ-формул на языке Пролог необходимо оценивать не только временные, но и невременные логические операторы. Для этого выражения должны быть записаны в клаузальной форме и переведены в прологовские клозы. Ниже приводятся прологовские клозы для оценки следующих невременных логических операторов: отрицания (NOT), дизъюнкции (OR), конъюнкции (AND), импликации (IMPLIES), эквивалентности (EQU): not(P,S):-P=..T,insert(T,[S],P0),P01=..P0,call(P01), !, fail. not(P,S). or(P1,P2,S):-P1=..T,insert(T,[S],P0),P01=..P0,call(P01),!. or(P1,P2,S):-P2=..T,insert(T,[S],P0),P02=..P0,call(P02).
and(P1,P2,S):-P1=..T,insert(T,[S],P0),P01=..P0,call(P01), P2=..K,insert(K,[S],P00),P02=..P00,call(P02). implies(P1,P2,S):-P1=..T,insert(T,[S],P0),P01=..P0,call(P01), not(P2,S),!,fail. implies(P1,P2,S). equ(P1,P2,S):-P1=..T,insert(T,[S],P0),P01=..P0,call(P01), P2=..K,insert(K,[S],P00),P02=..P00,call(P02), !. equ(P1,P2,S):-not(P1,S), not(P2,S).
3.3. Исследование сетевых моделей Ниже приводятся результаты исследований сетевых моделей, рассмотренных в главе 2, с помощью временной логики. Временная логика выступает в роли языка описания доказываемых свойств системы. Следует отметить, что ниже будут использоваться только безусловные временные операторы. При записи формулы для всех предикатов будет опускаться аргумент, определяющий состояние системы. 3.3.1. Доказательство свойств сетевых моделей Свойства сетевых моделей были определены в разд. 1.2. Для доказательства свойств определим предикат enable. Истинное значение выражения enable(t,s) показывает, что в состоянии s разрешен переход t. Этот предикат истинен в состоянии s, если существует дуга из состояния s в состояние s1. Прологовское определение этого предиката следующее: enable(T,S):-arc(S,T,S1). Свойство живости
Для доказательства того, что переход t сетевой модели живой, используется следующая ЛДВ-формула: ╞ init → ALL(POT(enable(t))). Иными словами, переход t живой, если во всех состояниях сетевой модели, начинающей свое функционирование из начального состояния, переход t потенциально разрешен. На языке Пролог данная формула может быть проинтерпретирована следующим образом: live(T):- init(S),implies(init,all(pot(enable(T))),S). Если на запрос live(t) Пролог-система ответит yes, то переход t является живым. Следует заметить, что может быть составлено несколько ЛДВформул для проверки свойства живости перехода. Так, например, с использованием эквивалентных соотношений, приведенных в разд. 3.1, могут быть получены следующие формулы: ╞ init → ALL(∼ALL(∼enable(t))), ╞ init → ∼POT(ALL(∼enable(t))), ╞ init → ∼POT(∼POT(enable(t))). Доказательство того, что сетевая модель является живой, производится с помощью следующей формулы: ∀ t [init → ALL(POT(enable(t)))]. Заменяя квантор всеобщности квантором существования, получаем: ∼∃ t [∼(init → ALL(POT(enable(t))))]. Трансформированная таким образом ЛДВ-формула интерпретируется на языке Пролог так: liveness:-init(S),transition(T), not(implies(init,all(pot(enable(T)))),S), !, fail. liveness. Eсли на запрос liveness Пролог-система ответит yes, то исследуемая сетевая модель является живой. Свойство мертвости
Для доказательства того, что переход t сетевой модели мертвый, используется следующая ЛДВ-формула: ╞ init → ALL(∼enable(t)). Иными словами, переход t мертвый, если во всех состояниях сетевой модели, начинающей свое функционирование из начального состояния, переход t не разрешен. На языке Пролог данная формула может быть проинтерпретирована следующим образом: dead(T):- init(S),implies(init,all(not(enable(T))),S). Если на запрос dead(t) Пролог-система ответит yes, то переход t является мертвым. Доказательство того, что сетевая модель производится с помощью следующей формулы:
является
мертвой,
╞ ∀t [init → ALL(∼enable(t))]. Заменяя квантор всеобщности квантором существования, получаем: ╞ ∼∃t [∼(init → ALL(∼enable(t)))]. Интерпретация данной формулы на языке Пролог следующая: deadness:- init(S),transition(T), not(implies(init,all(not(enable(T)))),S), !,fail. deadness. Если на запрос deadness Пролог-система ответит yes, то исследуемая сетевая модель является мертвой. Свойство потенциальной живости Для доказательства того, что переход t сетевой модели потенциально живой, используется следующая ЛДВ-формула: ╞ init → POT(ALL(POT(enable(t)))). Иными словами, переход t потенциально-живой, если возможна такая ситуация, когда он всегда имеет возможность стать разрешенным. Следует отметить, что множество потенциально живых переходов входит в множество условно-живых переходов, поэтому потенциально живой переход также является и условно-живым.
На языке Пролог данная формула может быть проинтерпретирована следующим образом: potlive(T):- init(S),implies(init,pot(all(pot(enable(T)))),S). Если на запрос potlive(t) Пролог-система ответит yes, является потенциально живым.
то переход t
Доказательство того, что сетевая модель является потенциально живой, производится с помощью следующей формулы: ╞ ∀t [init → POT(ALL(POT(enable(t))))]. Заменяя квантор всеобщности квантором существования, получаем: ╞ ∼∃t [∼(init → POT(ALL(POT(enable(t)))))]. Интерпретация данной формулы на языке Пролог следующая: potliveness:- init(S),transition(T), not(implies(init,pot(all(pot(enable(t))))),S), !,fail. potliveness. Если на запрос potliveness Пролог-система ответит yes, то исследуемая сетевая модель является потенциально живой.
Детерминизм срабатывания переходов Как следует из правил функционирования сетей Петри, выбор перехода для срабатывания из множества разрешенных переходов недетерминирован. Для некоторых приложений сетевых моделей полезно знать, срабатывает ли конкретный переход в результате детерминированного или недетерминированного выбора. Детерминированный выбор перехода t случается в том случае, когда переход t появляется в списке разрешенных переходов лишь в единственном числе. Для определения этого свойства с использованием временной логики введем предикат fired. Истинное значение выражения fired(t,s) означает, что при срабатывании перехода t сетевая модель переходит в состояние s. Иными словами, существует состояние s1, из которого есть дуга, помеченная переходом t, ведущая в состояние s. Определим данный предикат на языке Пролог следующим образом: fired(T,S):- arc(S1,T,S).
Для доказательства того, что при срабатывании перехода t отсутствует недетерминированный выбор, может использоваться следующая ЛДВформула: ╞ init → ALL(enable(t)→PRETILDA(fired(t))). Иными словами, при срабатывании перехода t отсутствует недетерминированный выбор, если во всех состояниях сетевой модели, начинающей свое функционирование из начального состояния из разрешенности перехода t на следующем шаге всегда следует его срабатывание. Следует заметить, что из состояния может выходить только одна дуга, помеченная переходом t. На языке Пролог данная формула может быть проинтерпретирована следующим образом: determ(T):- init(S),implies(init,all(implies(enable(T), pretilda(fired(T)))),S). Если на запрос determ(t) Пролог-система ответит yes, то переход t cрабатывает всегда детерминированно.
3.3.2. Система с общими ресурсами Определим, отсутствуют ли в системе из 2-х параллельных процессов, разделяющих пару общих ресурсов (рис.2.1), тупики. Под тупиком подразумевается такая ситуация, когда ни один из процессов не может развиваться. Отсутствие тупиков является одним из основных свойств систем с параллельными процессами. Для доказательства отсутствия тупиков достаточно показать, что соответствующая сетевая модель жива. Определим предикат transition, используемый в теле клоза с заголовком liveness, следующим образом: transition(t11). transition(t12). transition(t13). transition(t21). transition(t22). transition(t23).
На целевое утверждение liveness Пролог-интерпретатор отвечает no, что указывает на присутствие в рассматриваемой системе тупиков.
3.3.3. Задача взаимного исключения Покажем, что сетевая модель, представленная на рис.2.3, описывает задачу взаимного исключения. Как было отмечено в разд. 2.2, одним из основных свойств критической области является то, что одновременно в ней может находиться не более одного процесса (свойство взаимного исключения). Сформулируем данное требование в терминах сетевых моделей и временной логики. Определим предикат crit следующим образом: crit(I,S):-inlist(cr(I),S). Этот предикат истинен, если позиция cr(I) входит в состояние S. Истинное значение выражения crit(I,S) интерпретируется как нахождение iго процесса в критической области. С использованием этого предиката можно написать следующую формулу временной логики, выражающую свойство взаимного исключения: init ╞ ALL ∼(crit(a) & crit(b)) или, используя теорему дедукции, ее можно переписать в виде: ╞ init→ ALL ∼(crit(a) & crit(b)), где init - предикат, определяющий начальное состояние системы. Данная формула будет истинной, если во всех состояниях системы, начиная от начального, всегда будет выполняться следующее условие: позиции cr(a) и cr(b) одновременно не маркированы. Интерпретация данной следующей:
формулы на языке Пролог может быть
implies(init,all(not(and(crit(a),crit(b)))),S). Выполнение данного целевого утверждения приводит к положительному результату (true), что можно интерпретировать как наличие свойства взаимного исключения. Покажем выполнение следующего требования, предъявляемого к системе в данной задаче (см. разд. 2.2): "Решение о вхождении процессов в их критические области ... не откладывается на неопределенное время, а является конечным по времени".
Для этого определим предикат outside следующим образом: outside(I,S):-inlist(idle(I),S). Этот предикат истинен, если позиция idle(I) входит в состояние S. Истинное значение выражения outside(I,S) интерпретируется как нахождение i-го процесса вне критической области. С использованием этого предиката можно написать следующие формулы временной логики, выражающие отмеченное требование: ╞ init→ALL(outside(a)→INEV(crit(a)) и ╞ init→ALL(outside(b)→INEV(crit(b)). Интерпретация первой из этих двух формул на языке Пролог следующей:
будет
implies(init,all(implies(req(a),inev(crit(a)))),S). Вторая формула представляется аналогичным образом. данных Пролог-выражений показала их истинность, отмеченное требование выполняется.
Интерпретация следовательно,
Докажем отсутствие тупиков в данной системе. Предикат transition, используемый в теле клоза liveness, определяется следующим образом: transition(T0):- index(S),tr(T),T0=..[T,S]. index(a). index(b). tr(seize). tr(release). В результате выполнения целевого утверждения интерпретатор выдает yes (цель достигнута). Значит отсутствуют.
liveness Прологтупики в системе
3.3.4. Задача "обедающие философы" Докажем отсутствие ситуации голодной смерти философов (см. рис.2.6), иначе - отсутствие тупиков. Определим предикат transition, используемый в клозе liveness cледующим образом: transition(T0):- philosopher(S),tr(T),T0=..[T,S]. philosopher(1).
philosopher(2). philosopher(3). philosopher(4). philosopher(5). tr(get). tr(put). Целевое утверждение liveness в этом случае истинно, ситуация голодной смерти отсутствует.
следовательно,
Докажем наличие ситуации голодания в представленной системе, или как ее еще называют, ситуации оттеснения. Определим предикат thinking следующим образом: thinking(I,S):- inlist(think(I),S). Истинное значение выражения thinkihg(I,S) размышление и желание i-го философа пообедать.
интерпретируется
как
Определим предикат eating cледующим образом: eating(I,S):-inlist(eat(I),S). Истинное значение предиката интерпретируется как философа в состоянии потребления пищи.
пребывание
Для доказательства наличия оттеснений предлагается формула:
i-го
следующая
╞∃i ∼(init→ALL(thinking(i)→INEV(eating(i)))), истинное значение которой будет свидетельствовать о наличии оттеснений. Интерпретация данной формулы на языке Пролог будет следующей: starvation_free:-philosopher(I), not(implies(init,all(implies(req(I),inev(eating(I))))),S),!. starvation_free:-fail. На запрос starvation_free Пролог-система ответит yes, что означает, что в системе имеет место ситуация оттеснения. 3.3.5. Алгоритм взаимного исключения в РВС Докажем свойство взаимного исключения. Взаимное исключение имеет место, если для всех вариантов функционирования системы, стартующей
из начального состояния, никогда не наблюдается одновременное нахождение двух узлов в критических областях. Определим предикат crit следующим образом: crit(I,S):- inlist(critical(I,H),S). Истинное значение выражения crit(I,S) интерпретируется как нахождение i-го узла в критической области. ЛДВ-формула для проверки свойства взаимного исключения имеет вид: ╞ init→ALL∼(crit(site_a) & crit(site_b)). Запрос mutual_exclusion для проверки указанного свойства на языке Пролог может иметь следующий вид: mutual_exclusion:- init(S),implies(init,all(not( and(crit(site_a), crit(site_b)))),S). Введя целевое утверждение mutual_exclusion через некоторое время, Пролог-интерпретатор выдаст ответ yes, что означает, что верифицируемая система обладает свойством взаимного исключения. Докажем отсутствие блокировок в РВС, работающей в соответствии с алгоритмом взаимного исключения. В системе отсутствуют блокировки, если для всех вариантов функционирования системы, стартующей из начального состояния, при запросе узла на вхождение в критическую область, он (узел) рано или поздно, но неизбежно в нее войдет. Введем предикат req следующим образом: req(I,S):- inlist(request(I,J,H),S). Истинное значение выражения req(I,S) интерпретируется как готовность и желание i-го узла войти в свою критическую область. Для проверки отсутствия блокировок используется следующая ЛДВ-формула (для узла site_a): ╞ init→ALL(req(site_a)→INEV(crit(site_a)). Для узла site_b формула строится аналогично. Формулировку соответствующего запроса на языке Пролог можно определить следующим образом: starvation_free:- init(S),implies(init(S),all(implies( req(site_a),inev(crit(site_a)))),S). На запрос starvation_free Пролог-система отвечает yes, проинтерпретировать как отсутствие блокировок.
что можно
Для доказательства отсутствия тупиков определим предикат transition, используемый в теле клоза liveness, следующим образом: transition(T0):- site(S),tr(T),T)=..[T,S]. site(site_a). site(site_b). tr(send). tr(receive). tr(release). tr(i_reply). tr(w_reply). Результаты оценки целевого утверждения liveness позволяют сделать вывод, что тупики в системе отсутствуют.
3.3.6. Альтернативно-битовый протокол Считается, что протокол составлен корректно, если при реализации поведение системы отвечает следующим требованиям: 1. Отсутствие тупиков, т.е. таких состояний, когда цель еще не достигнута, а ни один объект не может изменить своего состояния. 2. Полнота - все предусмотренные спецификацией условия, действия и ситуации учтены, и соответствующие состояния достижимы. 3. Отсутствие бесполезных зацикливаний. 4. Недопустимость переполнений - реализация ограничений на количество переходов в отдельные состояния, обусловленные спецификацией. 5. Соответствие терминальных состояний поставленным в спецификациях целям. Эти пять условий определяют общую корректность, поскольку все протоколы обязательно должны удовлетворять этим условиям. Кроме общей корректности для каждого конкретного типа протоколов существует частная корректность, обусловленная спецификой протокола. В качестве условий, определяющих частную корректность АБ-протокола, можно выделить, например, следующие: "Линия не должна передавать более чем
один кадр одновременно", "Передатчик может находиться либо в состоянии готовности, либо в состоянии ожидания подтверждения, но не в обоих сразу". Докажем общую корректность АБ-протокола. Для этого докажем, что сетевая модель, представленная на рис.2.11, жива. Определим предикат transition, используемый в теле клоза liveness, следующим образом: transition(T0):- bit(S),tr(T),T0=..[T,S]. bit(zero). bit(one). tr(tsend). tr(recack). tr(propagate). tr(repeata). tr(reception). tr(loss). tr(repeatm). На утверждение liveness Пролог-интерпретатор следовательно, АБ-протокол в общем корректен.
отвечает
yes,
Покажем выполнение условия частной корректности, согласно которому линия не должна передавать более чем один кадр одновременно. Из сетевой модели на рис.2.11 видно, что среда передачи определяется позициями send и receive. Маркировка любой из этих позиций означает нахождение в среде передачи кадра(ов). Число кадров в среде передачи определяется как M(send) + M(receive), где функция М в данном случае ставит в соответствие позициям сетевой модели численное значение маркировки. Упомянутое требование в терминах сетевой модели формулируется следующим образом: всегда должно выполняться неравенство: 0 ≤ M(send)+M(receive) ≤ 1. C использованием временной логики данное условие может выражено в виде следующей формулы: ╞ init→ALL(M(send)=0 & M(receive)=0 ∨ M(send)=0 & M(receive)=1
быть
∨ M(send)=1 & M(receive)=0). Выразим данную формулу на языке Пролог. Введем предикат num(E,N,L) для определения N - числа вхождений элемента E в список L, следующим образом: num(E,0,[]). num(E,N,[E|R]):-num(E,N1,R), N is N1+1. num(E,N,[F|R]):-num(E,N,R). С использованием данного предиката вышеприведенная ЛДВ-формула представляется на языке Пролог следующим образом: implies(init,all(or(or(and(num(send(_,_,_),0), num(receive(_,_,_),0)),and(num(send(_,_,_),0), num(receive(_,_,_),1))),and(num(send(_,_,_),1), num(receive(_,_,_),0)))),S). Данное утверждение достигается, следовательно, отмеченное условие выполняется. Покажем выполнение условия частной корректности АБ-протокола, согласно которому передатчик может находиться либо в состоянии готовности, либо в состоянии ожидания подтверждения (но не в обоих сразу). Как было отмечено в разд.2.5, условие M(send)=1 интерпретируется как нахождение передатчика в состоянии готовности, а M(wait)=1 - в состоянии ожидания подтверждения. В терминах сетевых моделей данное условие корректности может быть сформулировано следующим образом: всегда должно выполняться равенство: M(psend)+M(wait)=1. Иными словами, позиции psend и wait образуют инвариант. Формула временной логики, следующая:
представляющая данное утверждение,
╞ init→ALL(M(psend)=0 & M(wait)=1 ∨ M(psend)=1 & M(wait)=0)). Интерпретация данной формулы на языке Пролог следующая: implies(init(all(or(and(num(psend(_),0),num(wait(_),1)), and(num(psend(_),1),num(wait(_),0)))),S). Данное целевое утверждение достигается, условие выполняется.
следовательно, отмеченное
Проверим истинность следующего утверждения: "В любом случае переданный кадр рано или поздно, но неизбежно подтвердится". Для этого определим предикаты sended и confirmed. sended(S):-inlist(wait(B),S). confirmed(S):-inlist(psend(B),S). Истинность первого предиката указывает на то, что кадр передан, а второго - на то, что предыдущий переданный кадр подтвержден. Формула временной логики, представляющая данное утверждение, записывается следующим образом: ╞ init→ALL(sended→INEV(confirmed)). На языке Пролог данная формула интерпретируется следующим образом: implies(init,all(implies(sended,inev(confirmed)))),S). При оценке данного утверждения будет получен ложный результат. Таким образом, приведенное выше утверждение ложно. Объяснение может быть следующим: при высоком уровне помех в канале связи существует ситуация, когда информационный кадр или подтверждение постоянно искажаются. В результате этого возникают бесконечные повторные передачи и в итоге переданный кадр так и не будет подтвержден. Могут быть составлены и другие утверждения, касающиеся функционирования АБ-протокола, например, такие как "возможно некоторое время четности передатчика и приемника не будут совпадать", "в состоянии ожидания передатчик ожидает подтверждения той же четности" и т.д.
Литература 1. Кларк К., Маккейб Ф. Введение в логическое программирование на микро-Прологе. - М.: Радио и связь, 1987. - 312 с. 2. Логический подход к искусственному интеллекту: от классической логики к логическому программированию /Тейз А. и др. - М.: Мир, 1990. - 432 с. 3. Грэй П. Логика, алгебра и базы данных. - М.: Машинострое-ние, 1989. 368 с. 4. Лорьер Жан-Луи. Системы искусственного интеллекта. - М.: Мир, 1991. - 568 с. 5. Хоггер К. Введение в логическое программирование. - М.: Мир, 1988. - 348 с. 6. Братко И. Программирование на языке Пролог для искусственного интеллекта. - М.: Мир, 1990. - 559 с. 7. Доорс Дж. и др. Пролог - язык программирования будущего. -М.: Финансы и статистика, 1990. - 144 с. 8. Ин Ц., Соломон Д. Использование Турбо-Пролога. - М.: Мир, 1990. 9. Искусственный интеллект: В 3-х кн. Кн. 3. Программные и аппаратные средства. Справочник/Под ред. В.Н. Захарова, В.Ф. Хорошевского. - М.: Радио и связь, 1990. - 368 с. 10. Стерлинг Л., Шапиро Э. Искусство программирования на языке Пролог. - М.: Мир, 1990. - 335 с. 11. Малпас Дж. Реляционный язык Пролог и его применение.- М.: Наука, 1990.- 464 с. 12. Кузнецов В.Е. Представление в ЭВМ неформальных процедур. Продукционные системы. - М.: Наука, 1989. 13. Нейлор К. Как построить свою экспертную систему. - М. : Энергоатомиздат, 1991. - 286 с. 14. Попов Э.В. Экспертные системы. - М.: Наука, 1987. - 288 с. 15. Уотермен Д. Руководство по экспертным системам. - М. : Мир, 1989. 388 с. 16. Экспертные системы. Принципы работы и примеры /А. Брукинг и др., под ред. Р. Форсайта. - М.: Радио и связь, 1987. - 224 с. 17. Элти Дж., Кумбс М. Экспертные системы: концепции и примеры. - М.: Финансы и статистика, 1987. - 192 с. 18. Клоксин У., Меллиш К. Программирование на языке Пролог : Пер. с англ. - М.: Мир, 1987. - 336 с. 19. Макаллистер Дж. Искусственный интеллект и Пролог на микро-ЭВМ: Пер. с англ. - М.: Машиностроение, 1990.- 240 с.
20. Язык Пролог в пятом поколении ЭВМ. Сб. статей. - М.: Мир,1988. - 501 с. 21. Пролог - язык программирования будущего: Пер. с англ./ Доорс Дж. и др. - М.: Финансы и статистика, 1980. - 142 с. 22. Claudia M. Prolog programming. Applications for database systems, expert systems, and natural language systems. - Addison-Wesley publishing company. - 1986. - 325 P. 23. Питерсон Дж. Теория сетей Петри и моделирование сис-тем. - М.:Мир, 1984. - 263 с. 24. Соловьев Г.Н.,Никитин В.Д. Операционные системы ЭВМ: Учеб.пособие. - М.:Высшая школа, 1989. - 255 с. 25. Шоу А. Логическое проектирование операционных сис-тем: Пер.с англ. - М.: Мир, 1981. - 360 с. 26. Вычислительные сети и сетевые протоколы / Д.Дэвис, Д.Барбер, У.Прайс и др. - М.: Мир, 1983. - 560 с. 27. Зайцев С.С. Описание и реализация протоколов сетей ЭВМ. - М.: Наука, 1989. - 272 с. 28. Бандман О.Л. Сети Петри и корректность протоколов передачи данных //Вычислительные системы: Межвуз.сб.науч.тр. - Новосибирск, 1985. С.29-51 29. Дубинин В.Н.,Зинкин С.А. Спецификация и верификация процессов обмена информацией в вычислительных системах и сетях: Учеб.пособие. - Пенза: Изд-во Пенз.политехн.ин-та, 1992. - 95 с. 30. Cтобо Д.Ж. Язык программирования Пролог. - М.: Радио и связь, 1993. - 368 с. 31. Системы дедуктивного вывода и решение логических задач. Методические указания. Составители: С.Л.Зверев, В.Н.Дубинин. Пенза: ПГТУ, 1993. - 60 с. 32. Genrich H.J., Lautenbach . System modelling with high-level Petri nets // Theor.Comput.Sci. - 1981. - v.13, N 1. -P. 109 - 136 33. Azema P.,Juanole G.,Sandus E.,Moutbernard M. Specification and verification of distributed systems using Prolog interpreted Petri nets // Proc. 7th Int. Conf. Software Eng. - 1984. -P.510 - 518 34. Papapanagiotakis G.,Azema P.,Pradin-Chezalviel B. Propositional branching time temporal logic in Prolog // 5th Annu.Int.Phoenix. Conf. Comput. and Commun. - 1986. - P.371 - 377 35. Berthelot G.,Terrat R. Petri nets theory for the correct-ness of protocols // IEEE Transactions on communications. - Vol. Com-30, N 12. - 1982. P.2497 - 2505 36. Марселлус Д. Программирование экспертных систем на Турбо Прологе. - М.: Финансы и статистика, 1994. - 256 с.
37. Дубинин В.Н.,Гусаров С.В. Сетевые спецификации и моделирование параллельных взаимодействующих интеллектуальных систем с использованием языков искусственного интеллекта // Материалы междунар. научн.-техн. конф. "Новые информационные технологии и системы". - Пенза, 1994. - С.72 38. Перспективы развития вычислительной техники: В 11 кн.: Справ.пособие / Под ред.Ю.М.Смирнова. Кн. 1: Информационные семантические системы / Н.М.Соломатин . - М.: Высш.шк., 1989. - 127 с. 39. Перспективы развития вычислительной техники: В 11 кн.: Справ.пособие / Под ред.Ю.М.Смирнова. Кн. 2: Интеллектуализация ЭВМ / Е.С.Кузин, А.И.Ройтман, И.Б.Фоминых, Г.К.Хахалин. - М.: Высш.шк., 1989. - 159 с. 40. Voss K. Stepwise specification of a distributed database system // Proc. 2nd Int.Conf.Distrib.Comput.Syst. - Paris, 1981. - P. 218-226 41. Вашкевич Н.П.,Дубинин В.Н.,Зверев С.Л.,Зинкин С.А. Проектирование интеллектуальных систем управления массовой памятью на основе функционального подхода // Моделиране и симулиране на човешката памет - МНЕМО'89: Тез. докл. III науч.-техн. конф. с международным участием "ДЗУ'89". - Варна (НРБ), 1989. - С.24-26 42. Дубинин В. Н., Зинкин С.А. Экспертная система для верификации и проектирования алгоритмов функционирования систем управления внешней памятью ЭВМ // Практика применения баз данных для решения информационно-поисковых задач и задач управления. - Пенза: ПДНТП, 1989. - С.28-29 43. Вашкевич Н.П.,Дубинин В.Н. Моделирование и верификация систем управления внешней памятью ЭВМ с использованием системы продукций // Базы данных и экспертные системы в АСНИ: Тез. докл. конф. - Севастополь, 1990 44. Дубинин В.Н.,Зверев С.Л.,Зинкин С.А. Разработка интеллектуальной САПР систем управления внешней памятью высокопроизводительных ЭВМ // Программное обеспечение ЭВМ: Тез.докл. III междунар. науч.техн. конф. Секция 6. - Тверь,1990. - С.64-66 45. Вашкевич Н.П.,Дубинин В.Н.,Зинкин С.А. Использование методов искусственного интеллекта при проектировании интеллектуальных систем управления внешней и массовой памятью ЭВМ // Техническая кибернетика. Изв. АН СССР. - 1991. - N 5. - С.63-74 46. Дубинин В.Н.,Зверев С.Л.,Зинкин С.А. Аппаратная поддержка функций управления базами знаний в системах искусственного интеллекта // Вычислительная техника в автоматизированных системах контроля и управления: Межвуз.сб.науч.тр. - Пенза, ППИ. - 1991. - С.6672
47. Дубинин В.Н. Построение экспертных систем для верификации и моделирования коммуникационных протоколов // Материалы Межреспубл. конф. "Повышение эффективности средств обработки информации на базе математического и машинного моделирования". Тамбов, 1993. - С.263-264 48. Дубинин В.Н. Язык логических запросов к базе данных о переходах состояний для верификации дискретных систем // Материалы междунар. науч.-техн. конф. "Новые информационные технологии и системы" (НИТС'94). - Пенза,1994. - С.59 49. Дубинин В.Н. Интерпретация логических запросов, основанных на временной логике // Материалы 2-й международной науч.- техн. конф. "Новые информационные технологии и системы" (НИТС'96), ч. 1. Пенза : ПГТУ. - 1994. - С.73-74 50. Дубинин В.Н. Вычисление логических запросов, основанных на временной логике. - Пензенский гос. техн. ун-т. - Пенза, 1996. - 54 с. Деп. в ВИНИТИ 14.02.96, N 488-В96 51. Дубинин В.Н. ПЕТРИС - комплекс программ для графического моделирования расширенных сетей Петри / Пензенский гос. техн. ун-т. Пенза, 1996. - 34 с. - Деп. в ВИНИТИ 23.07.96; N 2502-В96 52. Программирование на языке Лисп: Методические указания / Составитель: В.Н.Дубинин. - Пенза: Изд-во Пенз.гос.техн.ун-та, 1996. 38 с. 53. Zinkin S.A. Using an intelligent storage for building knowledge representation systems // IV Int. Conf.Disc Storage Devices. - Costenets (Bulgaria),1990. - P.50-51 54. Zinkin S.A. Toward intellectual mass memory design for building highperformance computer systems and networks // Proc. Second Int. Conf. Sci. & Techn. "Current Problems of Fundamental Sciences", Part 14. - M.,1994 55. Zinkin S.A. The software and hardware architecture of a tightly-co- upled interface for a knowledge representation system // Proc. Int. Conf. Sci. & Techn. "New information technologies and systems" (NITS'94). - Penza, 1994. - P.50 56. Zinkin S.A. Design the intellectual mass memory for building highperformance computer systems and networks // Proc. Int. Conf. Sci. & Techn. "New information technologies and systems" (NITS'94). - Penza, 1994. - P.85 57. Vashkevitch N.P., Derbenyov S.A., Zinkin S.A. Prolog as a formalism for nondeterministic automata simulation // Proc. Int. Conf. Sci. & Techn. "New information technologies and systems" (NITS'94). - Penza, 1994. - P.39-40 58. Vashkevitch N.P., Derbenyov S.A., Zinkin S.A. Experiences in Prologbased hardware representation formalism // Proc. Int. Conf. Sci. & Techn. "New information technologies and systems" (NITS'94). - Penza, 1994. P.41-42
59. Dubinin V.N. SIMS-M - a software package for design and implementation of distributed systems on the basis of local area network // Proc. Int. Conf. Sci. & Techn. "New information technologies and systems" (NITS'94). Penza, 1994. - С.77-78 60. Tuzilov I.V., Dubinin V.N., Finogeev A.G. Ontological knowledge representation // Proc. Int. Conf. Sci. & Techn. "New information technologies and systems" (NITS'94). - Penza, 1994. - P.52 61. Vashkevich N.P., Dubinin V.N. Net formalism based tools for design, verification and implementation of distributed systems // Proc. EAST - WEST Int. Conf. "Information Technology in Design" (EWITD'94), Part 2. - M., 1994, P.170-174. 62. Dubinin V.N. Design of distributed CAD systems on the basis of local area network // EAST-WEST Int.Conf. "Information Technology in Design" (EWITD'96). - M.: 1996. - P.152-155 63. Zinkin S.A. Systolic nets modelling with simulation programs of different types // Proc. EAST - WEST Int. Conf. "Information Technology in Design" (EWITD'96). - M.: 1996. - P.87-90 64. Zinkin S.A. The software and hardware architecture of a tightly-coupled interface for a knowledge representation system // Proc. EAST - WEST Int. Conf. "Information Technology in Design" (EWITD'96). - M., 1996. - P.8790 65. Дубинин В.Н. Децентрализованное управление распределенными данными в локальной вычислительной сети: спецификация, моделирование, реализация и применение в распределенных вычислениях / Пензенский гос. техн. ун-т. - Пенза, 1997. - 78 с. - Деп. в ВИНИТИ 10.06.97, N 1946-B97.
СОДЕРЖАНИЕ Введение Глава 1. МОДЕЛИРОВАНИЕ ПАРАЛЛЕЛЬНЫХ ДИСКРЕТНЫХ СИСТЕМ С ИСПОЛЬЗОВАНИЕМ ПРЕДИКАТНЫХ СЕТЕЙ, ИНТЕРПРЕТИРУЕМЫХ НА ЯЗЫКЕ ПРОЛОГ 1.1. Предикатные сети 1.2. Некоторые свойства сетевых моделей 1.3. Представление предикатных сетей на языке Пролог 1.4. Построение графа достижимых состояний с помощью языка Пролог Глава 2. ПРИМЕРЫ МОДЕЛИРОВАНИЯ ВЫЧИСЛИТЕЛЬНЫХ СИСТЕМ И ПРОЦЕССОВ С ИСПОЛЬЗОВАНИЕМ ПРЕДИКАТНЫХ СЕТЕЙ 2.1. Система с общими ресурсами 2.2. Задача взаимного исключения 2.3. Задача об обедающих философах 2.4. Алгоритм взаимного исключения в распределенной вычислительной системе 2.5. Альтернативно-битовый протокол Глава 3. ВЕРИФИКАЦИЯ ВЫЧИСЛИТЕЛЬНЫХ СИСТЕМ И ПРОЦЕССОВ С ИСПОЛЬЗОВАНИЕМ ВРЕМЕННОЙ ЛОГИКИ, ИНТЕРПРЕТИРУЕМОЙ НА ЯЗЫКЕ ПРОЛОГ 3.1. Логика дерева вычислений 3.2. Интерпретация временной логики на языке Пролог 3.2.1. Реализация POT-оператора 3.2.2. Реализация ALL-оператора 3.2.3. Реализация других временных операторов 3.2.4. Реализация невременных логических операторов 3.3. Исследование сетевых моделей 3.3.1. Доказательство свойств сетевых моделей 3.3.2. Система с общими ресурсами 3.3.3. Задача взаимного исключения 3.3.4. Задача об обедающих философах 3.3.5. Алгоритм взаимного исключения в распределенной вычислительной системе 3.3.6. Альтернативно-битовый протокол Литература