RU2480819C2 - Method of optimising work with linked lists - Google Patents

Method of optimising work with linked lists Download PDF

Info

Publication number
RU2480819C2
RU2480819C2 RU2011126322/08A RU2011126322A RU2480819C2 RU 2480819 C2 RU2480819 C2 RU 2480819C2 RU 2011126322/08 A RU2011126322/08 A RU 2011126322/08A RU 2011126322 A RU2011126322 A RU 2011126322A RU 2480819 C2 RU2480819 C2 RU 2480819C2
Authority
RU
Russia
Prior art keywords
list
item
processes
reading
deleted
Prior art date
Application number
RU2011126322/08A
Other languages
Russian (ru)
Other versions
RU2011126322A (en
Inventor
Андрей Владимирович Собко
Original Assignee
Закрытое акционерное общество "Лаборатория Касперского"
Priority date (The priority date is an assumption and is not a legal conclusion. Google has not performed a legal analysis and makes no representation as to the accuracy of the date listed.)
Filing date
Publication date
Application filed by Закрытое акционерное общество "Лаборатория Касперского" filed Critical Закрытое акционерное общество "Лаборатория Касперского"
Priority to RU2011126322/08A priority Critical patent/RU2480819C2/en
Publication of RU2011126322A publication Critical patent/RU2011126322A/en
Application granted granted Critical
Publication of RU2480819C2 publication Critical patent/RU2480819C2/en

Links

Images

Landscapes

  • Information Retrieval, Db Structures And Fs Structures Therefor (AREA)

Abstract

FIELD: information technology.
SUBSTANCE: method of providing read processes continuous access to a linked list which contains one write process and at least one read process and in which upon deleting the last list element: all read processes obtain access to the list without waiting and are divided into read processes which started work with the list before the write process switched to the last list element, and read processes which started work with the list after the write process switched to the last list element, wherein: a) read processes which started work with the list before the write process switched to the last list element are executed for the number of list elements containing the last element; b) read processes which started work with the list after the write process switched to the last list element are executed for the number of list elements which do not contain the last element; wherein the write process deletes the last list element only after all read processes which started work with the list before the write process switched to the last element complete work with the list.
EFFECT: optimising work of write and read processes with linked list by providing read processes continuous access to the list while maintaining integrity of the data obtained by read processes.
6 cl, 7 dwg

Description

Область техникиTechnical field

Изобретение относится к способам выборки, адресации или распределения данных в системах или архитектурах памяти и, в частности, к способам оптимизации работы со связными списками.The invention relates to methods for fetching, addressing or distributing data in memory systems or architectures and, in particular, to methods for optimizing work with linked lists.

Уровень техникиState of the art

Все компьютерные системы имеют ограниченные ресурсы и, в частности, ограниченный объем памяти. По этой причине в случае, если в системе осуществляется несколько процессов, этим процессам приходится конкурировать за память. По этой же причине процессам приходится конкурировать за программные ресурсы. Примерами программных ресурсов могут служить разделяемые библиотеки и различные структуры данных.All computer systems have limited resources and, in particular, limited memory. For this reason, if several processes are carried out in the system, these processes have to compete for memory. For the same reason, processes have to compete for software resources. Examples of software resources include shared libraries and various data structures.

Одним из примеров структур данных является связный список. Под связным списком понимается структура данных, состоящая из элементов, каждый из которых содержит как собственные данные, так и одну или две ссылки на следующий и (или) предыдущий элемент списка. Все процессы, работающие со связными списками, условно разделяются на процессы записи и процессы чтения. К процессам записи относятся те процессы, которые производят изменения связного списка, в частности добавление новых элементов, удаление или изменение существующих элементов связного списка. К процессам чтения относятся процессы, предназначенные для получения данных из элементов связного списка.One example of data structures is a linked list. A linked list refers to a data structure consisting of elements, each of which contains both its own data and one or two links to the next and / or previous list item. All processes working with linked lists are conditionally divided into write processes and reading processes. Recording processes include those processes that make changes to the linked list, in particular adding new items, deleting or changing existing items in the linked list. Reading processes include processes designed to retrieve data from linked list items.

На Фиг.1 показана структурная схема варианта реализации связного списка. Связный список 100 состоит из элементов списка 110, 120, 130, 140 и 150. Каждый элемент связного списка содержит собственные данные и ссылку на следующий элемент списка. Так, элемент 110 содержит блок собственных данных 111 и ссылку 112 на следующий элемент списка 120. Элемент 120 содержит блок собственных данных 121 и ссылку 122 на следующий элемент списка 130. Элемент 130 содержит блок собственных данных 131 и ссылку 132 на следующий элемент списка 140. Элемент 140 содержит блок собственных данных 141 и ссылку 142 на следующий элемент списка 150. Последний элемент списка 150 содержит только блок собственных данных 151.Figure 1 shows a structural diagram of a variant of implementation of a linked list. The linked list 100 consists of list items 110, 120, 130, 140 and 150. Each linked list item contains its own data and a link to the next list item. So, element 110 contains a block of own data 111 and a link 112 to the next element of the list 120. Element 120 contains a block of own data 121 and a link 122 to the next element of the list 130. Element 130 contains a block of own data 131 and a link 132 to the next element of the list 140. Element 140 contains an own data block 141 and a link 142 to the next element of the list 150. The last element of the list 150 contains only the own data block 151.

Примером применения связного списка может служить список доверенных процессов и потоков, используемый антивирусным программным обеспечением для определения процессов и потоков, проверки на вредоносность для которых не требуется.An example of using a linked list is the list of trusted processes and threads used by antivirus software to identify processes and threads for which malware testing is not required.

При одновременной работе процессов записи и чтения со связным списком возможно возникновение ситуации, когда получение данных процессом чтения из элемента связного списка будет производиться в момент его изменения процессом записи, что в итоге приведет к нарушению целостности получаемых данных. Для того чтобы избежать подобной ситуации, необходимо производить синхронизацию процессов чтения и записи.With the simultaneous operation of the writing and reading processes with the linked list, a situation may arise when the reading process receives data from the linked list item at the time it is changed by the write process, which ultimately leads to a violation of the integrity of the received data. In order to avoid this situation, it is necessary to synchronize the reading and writing processes.

В классических схемах задача синхронизации решается путем использования взаимного исключения. Суть использования взаимного исключения заключается в том, что в определенный момент времени с каждым из элементов связного списка может производить работу процесс только одного типа - либо записи, либо чтения. В зависимости от условий поставленной задачи приоритет в использовании взаимного исключения может принадлежать процессам одного из двух типов.In classical schemes, the synchronization problem is solved by using mutual exclusion. The essence of using mutual exclusion is that at a certain point in time, only one type of process can work with each element of the linked list — either writing or reading. Depending on the conditions of the task, the priority in using mutual exclusion may belong to one of two types of processes.

На Фиг.2 показана структурная схема работы процессов чтения и записи со связным списком. Процессы чтения 210 и 220 осуществляют чтение элементов 110 и 120 связного списка 100 соответственно. Процесс записи 230 осуществляет изменение элемента 130 связного списка 100. Для того чтобы была обеспечена целостность получаемых процессами чтения 210 и 220 данных, указанные процессы чтения должны дождаться завершения работы процесса записи 230 с элементом связного списка 130, прежде чем начать чтение этого элемента. Таким образом, приоритет в использовании взаимного исключения в случае, представленном на Фиг.2, принадлежит процессу записи.Figure 2 shows the structural diagram of the processes of reading and writing with a linked list. The reading processes 210 and 220 read the elements 110 and 120 of the linked list 100, respectively. The write process 230 changes the element 130 of the linked list 100. In order to ensure the integrity of the data received by the reading processes 210 and 220, these reading processes must wait for the completion of the write process 230 with the linked list element 130 before starting to read this element. Thus, the priority in using mutual exclusion in the case of FIG. 2 belongs to the recording process.

Однако метод использования взаимного исключения обладает одним существенным недостатком, а именно вероятностью возникновения ситуации, когда процесс одного из типов ожидает завершения работы процесса другого типа существенное количество времени. При этом в некоторых схемах реализации от скорости работы процессов со связными списками зависит быстродействие компьютерной системы. Так, например, происходит, когда связный список используется антивирусным программным обеспечением и содержит сведения о доверенных процессах и потоках, проверка на вредоносность для которых не требуется. В этом случае при возникновении в системе каждого нового процесса либо потока у существующего процесса антивирусное программное обеспечение прежде чем разрешить их исполнение производит проверку на предмет содержания сведений об указанных процессах либо потоках в связном списке. В случае если приоритет в использовании взаимного исключения принадлежит процессам записи, исполнение всех процессов и потоков в системе может задерживаться на время работы процесса записи со связным списком. В случае если приоритет в использовании взаимного исключения принадлежит процессам чтения, возможность внесения оперативных изменений в связный список будет утрачена.However, the method of using mutual exclusion has one significant drawback, namely, the likelihood of a situation when a process of one of the types expects the completion of the process of another type a significant amount of time. Moreover, in some implementation schemes, the speed of a computer system depends on the speed of the processes with linked lists. So, for example, it happens when a linked list is used by antivirus software and contains information about trusted processes and threads, for which malware testing is not required. In this case, when each new process or thread occurs in the system of an existing process, the anti-virus software checks for the content of information about the specified processes or threads in a linked list before allowing them to be executed. If the priority in using mutual exclusion belongs to the recording processes, the execution of all processes and threads in the system may be delayed for the duration of the recording process with the linked list. If the priority in using mutual exclusion belongs to the reading processes, the possibility of making operational changes to the linked list will be lost.

Поэтому для эффективной работы со связными списками необходимо использовать подход, который позволит избежать указанных ограничений и при котором сохраняется целостность получаемых процессами чтения данных.Therefore, to work effectively with linked lists, it is necessary to use an approach that will allow us to avoid these restrictions and which preserve the integrity of the data obtained by reading processes.

В патенте US 7536428 описана идея конкурентного доступа к связному списку процессов чтения и записи, основанная на использовании трех подсписков: подсписка чтения, подсписка записи и подсписка изменения. Все изменения вносятся процессом записи в подсписок изменения, в то время как процессы чтения имеют неограниченный доступ к подсписку чтения. Миграция изменений из подсписка изменения в подсписок чтения происходит только при условии, что с подсписком чтения не работают процессы чтения. В данной идее не обеспечивается оперативность вступления в силу изменений связного списка, так как данные изменения вступают в силу только в тот момент, когда с подсписком чтения не работает ни один процесс чтения.US Pat. No. 7,536,428 describes the idea of competitive access to a linked list of read and write processes based on the use of three sublists: a read list, a write list, and a change list. All changes are made by the writing process to the change sublist, while reading processes have unlimited access to the reading sublist. Migration of changes from the change sublist to the read sublist occurs only if the reading processes do not work with the read sublist. This idea does not ensure the speed of the entry into force of changes to the linked list, since these changes take effect only at the moment when no reading process works with the sublist.

В патенте US 6304924 описана идея организации доступа к связному списку процессов чтения и записи в порядке цикличной очереди. При работе с элементом связного списка каждый из двух типов процессов блокирует следующую за элементом часть списка для процессов другого типа. Таким образом, в данной идее процессы чтения и записи имеют ограниченный доступ к списку, так как вынуждены ждать завершения работы процессов другого типа с элементом связного списка.US Pat. No. 6,304,924 describes the idea of organizing access to a linked list of read and write processes in a cyclic queue. When working with a linked list item, each of the two types of processes blocks the next part of the list following the item for processes of another type. Thus, in this idea, reading and writing processes have limited access to the list, since they are forced to wait for the completion of the work of other types of processes with a linked list element.

В патентах US 7117502 и US 6760726 описаны идеи организации конкурентного доступа процессов чтения и записи к связному списку, которые объединяет один общий недостаток, а именно использование для синхронизации операций взаимного исключения.In patents US 7117502 and US 6760726 describes the idea of organizing competitive access of read and write processes to a linked list, which combines one common drawback, namely the use of synchronized mutual exclusion operations.

В патенте US 6360220 и заявке US 20020138706 описана идея предоставления общего доступа к структуре данных с использованием счетчика процессов чтения для определения момента времени, когда со структурой не работает ни один процесс чтения. В момент времени, когда со структурой данных не работают процессы чтения, возможно внесение изменений без риска потери целостности данных. Таким образом, в данном подходе приоритет использования взаимного исключения имеют процессы чтения, что приводит к невозможности оперативного внесения изменений.In the patent US 6360220 and the application US 20020138706 describes the idea of sharing a data structure using a counter of reading processes to determine the point in time when the structure does not work with any reading process. At the point in time when reading processes do not work with the data structure, it is possible to make changes without risking loss of data integrity. Thus, in this approach, the priority of using mutual exclusion is given to reading processes, which leads to the impossibility of prompt changes.

Таким образом, хотя перечисленные подходы направлены на решение определенных задач в области оптимизации работы со связными списками, они имеют ряд недостатков, которые были указаны выше. Настоящее изобретение позволяет более эффективно и результативно решить задачу предоставления процессам чтения непрерывного доступа к списку, при котором сохраняется целостность получаемых процессами чтения данных.Thus, although the listed approaches are aimed at solving certain problems in the field of optimizing work with linked lists, they have a number of drawbacks that were mentioned above. The present invention allows to more efficiently and effectively solve the problem of providing the reading processes with continuous access to the list, which preserves the integrity of the data obtained by the reading processes.

Раскрытие изобретенияDisclosure of invention

Настоящее изобретение предназначено для оптимизации работы со связными списками.The present invention is intended to optimize work with linked lists.

Технический результат настоящего изобретения заключается в оптимизации работы процессов записи и чтения со связными списками путем предоставления процессам чтения непрерывного доступа к списку при сохранении целостности получаемых процессами чтения данных для случая, когда со списком работает один процесс записи и, по крайней мере, один процесс чтения.The technical result of the present invention is to optimize the operation of the writing and reading processes with linked lists by providing the reading processes continuous access to the list while maintaining the integrity of the data obtained by the reading processes for the case when one writing process and at least one reading process work with the list.

В способе предоставления процессам чтения непрерывного доступа к связному списку, который содержит один процесс записи и, по крайней мере, один процесс чтения, при удалении элемента списка все процессы чтения без ожидания получают доступ к списку и разделяются на процессы чтения, которые начали работу со списком до того, как процесс записи перешел к последнему элементу списка, и на процессы чтения, которые начали работу со списком после того, как процесс записи перешел к последнему элементу списка. При этом процессы чтения, которые начали работу со списком до того, как процесс записи перешел к последнему элементу списка, выполняются для количества элементов списка, содержащих последний элемент. Процессы чтения, которые начали работу со списком после того, как процесс записи перешел к последнему элементу списка, выполняются для количества элементов списка, не содержащих последний элемент. При этом процесс записи удаляет последний элемент списка только после того, как все процессы чтения, которые начали работу со списком до того, как процесс записи перешел к последнему элементу, закончили работу со списком.In a way to provide reading processes with continuous access to a linked list that contains one writing process and at least one reading process, when a list item is deleted, all reading processes without waiting get access to the list and are divided into reading processes that started working with the list before the writing process went to the last element of the list, and to the reading processes that started working with the list after the writing process went to the last element of the list. In this case, the reading processes that started working with the list before the writing process moved to the last element of the list are performed for the number of list elements containing the last element. Reading processes that started working with the list after the writing process has moved to the last element of the list are performed for the number of list elements that do not contain the last element. In this case, the writing process deletes the last element of the list only after all the reading processes that started working with the list before the writing process moved to the last element have finished working with the list.

В вышеописанном способе процесс записи перемещает элемент, который необходимо удалить, в конец списка в случае, если элемент, который необходимо удалить, не является последним в списке.In the above method, the recording process moves the item to be deleted to the end of the list if the item to be deleted is not the last in the list.

Кроме того, в указанном способе процесс записи также производит логическое удаление элемента списка путем пометки элемента удаленным, при этом данные логически удаленного элемента списка игнорируются процессом чтения, и элемент остается в списке.In addition, in the indicated method, the recording process also logically deletes the list item by marking the item deleted, while the data of the logically deleted list item is ignored by the reading process, and the item remains in the list.

В способе предоставления процессам чтения непрерывного доступа к связному списку, который содержит один процесс записи и, по крайней мере, один процесс чтения, при добавлении нового элемента списка все процессы чтения без ожидания получают доступ к списку и разделяются на процессы чтения, которые начали работу со списком до добавления нового элемента, и на процессы чтения, которые начали работу со списком после добавления нового элемента. При этом процессы чтения, которые начали работу со списком до добавления нового элемента, выполняются для количества элементов списка, не содержащих добавляемый элемент. Процессы чтения, которые начали работу со списком после добавления нового элемента, выполняются для количества элементов списка, содержащих добавленный элемент.In a method of providing reading processes continuous access to a linked list that contains one writing process and at least one reading process, when a new list item is added, all reading processes without waiting gain access to the list and are divided into reading processes that started with list before adding a new element, and on reading processes that started working with the list after adding a new element. At the same time, reading processes that started working with the list before adding a new element are performed for the number of list elements that do not contain the element to be added. Reading processes that started working with the list after adding a new element are performed for the number of list elements containing the added element.

В указанном способе процесс записи добавляет новый элемент в конец списка, в случае если в списке нет логически удаленного элемента. В случае если в списке присутствует логически удаленный элемент, процесс записи добавляет новый элемент путем копирования данных нового элемента в логически удаленный элемент и снятия с логически удаленного элемента пометки удаленным.In the indicated method, the recording process adds a new element to the end of the list if there is no logically deleted element in the list. If a logically deleted element is present in the list, the recording process adds a new element by copying the data of the new element to the logically remote element and removing the mark from the logically deleted element as deleted.

Краткое описание чертежейBrief Description of the Drawings

Сопровождающие чертежи включены для обеспечения дополнительного понимания изобретения и составляют часть этого описания, показывают варианты осуществления изобретения и совместно с описанием служат для объяснения принципов изобретения.The accompanying drawings are included to provide a further understanding of the invention and form part of this description, show embodiments of the invention, and together with the description serve to explain the principles of the invention.

Заявленное изобретение поясняется следующими чертежами, на которых:The claimed invention is illustrated by the following drawings, in which:

Фиг.1 показывает структурную схему варианта реализации связного списка.Figure 1 shows a block diagram of an embodiment of a linked list.

Фиг.2 показывает структурную схему работы процессов чтения и записи со связным списком.Figure 2 shows the structural diagram of the processes of reading and writing with a linked list.

Фиг.3 показывает структурную схему варианта реализации способа оптимизации работы со связными списками.Figure 3 shows a block diagram of an embodiment of a method for optimizing work with linked lists.

Фиг.4 показывает структурную схему способа работы процесса чтения в способе оптимизации работы со связными списками.Figure 4 shows a structural diagram of a method for operating a reading process in a method for optimizing work with linked lists.

Фиг.5 показывает структурную схему способа работы процесса записи в способе оптимизации работы со списками при выполнении операции логического удаления элемента списка.5 shows a structural diagram of a method of operating a recording process in a method for optimizing work with lists when performing a logical deletion operation of a list item.

Фиг.6 показывает структурную схему способа работы процесса записи в способе оптимизации работы со списками при выполнении операции добавления элемента списка.6 shows a structural diagram of a method of operating a recording process in a method for optimizing work with lists in an operation of adding a list item.

Фиг.7 показывает структурную схему способа работы процесса записи в способе оптимизации работы со списками при выполнении операции удаления элемента списка.7 shows a structural diagram of a method of operating a recording process in a method for optimizing work with lists in a delete operation of a list item.

Описание вариантов осуществления изобретенияDescription of Embodiments

Объекты и признаки настоящего изобретения, способы для достижения этих объектов и признаков станут очевидными посредством отсылки к примерным вариантам осуществления. Однако настоящее изобретение не ограничивается примерными вариантами осуществления, раскрытыми ниже, оно может воплощаться в различных видах. Приведенное описание предназначено для помощи специалисту в области техники для исчерпывающего понимания изобретения, которое определяется только в объеме приложенной формулы.The objects and features of the present invention, methods for achieving these objects and features will become apparent by reference to exemplary embodiments. However, the present invention is not limited to the exemplary embodiments disclosed below, it can be embodied in various forms. The above description is intended to help a person skilled in the art for a comprehensive understanding of the invention, which is defined only in the scope of the attached claims.

На Фиг.3 показан один из вариантов реализации способа оптимизации работы со связными списками. Данный вариант реализации содержит систему управления списком 300 и собственно связный список 100. Система управления списком 300 в свою очередь состоит из устройства переключения активного счетчика 310, двух счетчиков процессов чтения 320 и 330 и устройства хранения количества элементов списка 340.Figure 3 shows one embodiment of a method for optimizing work with linked lists. This embodiment includes a list management system 300 and a linked list 100 itself. The list management system 300, in turn, consists of a switching device for an active counter 310, two reading process counters 320 and 330, and a storage device for the number of list items 340.

Каждый из двух счетчиков процессов чтения 320 и 330 предназначен для подсчета количества процессов чтения, которые в данный момент работают со списком. Подсчет производится путем увеличения на единицу значения счетчика в случае, если процесс чтения начал работу со списком, и уменьшения на единицу значения счетчика в случае, если процесс чтения закончил работу со списком, при начальном значении счетчика, равном нулю. В любой момент времени активным, то есть подсчитывающим количество начавших работу со списком процессов чтения путем увеличения своего значения на единицу, может быть только один из двух счетчиков. При этом, когда определенный процесс чтения завершает работу со списком, уменьшение своего значения на единицу производит тот счетчик, который был активен в момент начала работы данного процесса чтения со списком. Таким образом, равное нулю значение определенного счетчика будет свидетельствовать о том, что все процессы чтения, которые начали работу со списком в период времени, когда данный счетчик был активен, закончили работу со списком.Each of the two reading process counters 320 and 330 is designed to count the number of reading processes that are currently working with the list. Counting is done by increasing the counter value by one if the reading process has started working with the list, and decreasing by one the counter value if the reading process has finished working with the list, with the initial counter value equal to zero. At any given time, only one of two counters can be active, that is, counting the number of readers who started working with a list of reading processes by increasing their value by one. At the same time, when a certain reading process completes work with the list, decreasing its value by one produces the counter that was active when this reading process started with the list. Thus, the value of a certain counter equal to zero will indicate that all the reading processes that started working with the list in the period of time when this counter was active have finished working with the list.

В одном из вариантов реализации изобретения вместо каждого счетчика возможно использование отдельной пары счетчиков. При этом один счетчик из пары увеличивает свое значение на единицу в случае, если процесс чтения начал работу со списком, а второй счетчик из пары увеличивает свое значение на единицу в случае, если процесс чтения закончил работу со списком. Таким образом, когда все процессы чтения, начавшие работу со списком в период времени, когда определенная отдельная пара счетчиков была активна, заканчивают работу со списком, значения данной отдельной пары счетчиков становятся равны друг другу.In one embodiment of the invention, instead of each counter, it is possible to use a separate pair of counters. In this case, one counter from a pair increases its value by one if the reading process has started working with the list, and the second counter from a pair increases its value by one if the reading process has finished working with the list. Thus, when all the reading processes that started working with the list in the period of time when a certain separate pair of counters were active, finish working with the list, the values of this particular pair of counters become equal to each other.

Как указано выше, в любой момент времени только один из двух счетчиков 320 и 330 может быть активным. Поэтому устройство переключения активного счетчика 310 предназначено для одновременной деактивации активного счетчика и активации неактивного счетчика.As indicated above, at any time, only one of the two counters 320 and 330 can be active. Therefore, the switching device of the active counter 310 is designed to simultaneously deactivate the active counter and activate the inactive counter.

Устройство хранения количества элементов списка 340 предназначено для хранения и предоставления процессам чтения доступного для чтения количества элементов списка. Указанное доступное для чтения количество элементов списка процесс чтения проходит в ходе работы со связным списком 100. С целью обеспечения целостности получаемых процессами чтения данных в число доступных для чтения элементов списка, хранимое в устройстве 340, может не входить последний элемент списка, удаление либо добавление которого производится в определенный момент времени. Кроме того, как будет показано ниже, процесс чтения при начале работы со связным списком 100 после увеличения значения активного счетчика на единицу получает от устройства 340 количество элементов списка, которое ему необходимо пройти. Таким образом, каждый счетчик также подсчитывает количество процессов чтения, для которых доступно то количество элементов связного списка, которое хранилось в устройстве 340 в период времени, когда данный счетчик был активен.The device for storing the number of list items 340 is designed to store and provide reading processes with a readable number of list items. The indicated readable number of list items is read in the course of working with the linked list 100. In order to ensure the integrity of the data received by the reading processes, the list of items available for reading stored in the device 340 may not include the last list item, the removal or addition of which produced at a specific point in time. In addition, as will be shown below, the reading process when starting work with the linked list 100 after increasing the value of the active counter by one receives from the device 340 the number of list items that it needs to go through. Thus, each counter also counts the number of reading processes for which the number of linked list items that were stored in device 340 during the period of time when this counter was active is available.

В описываемом способе оптимизации работы со связными списками все операции, которые процессы записи производят с элементами связного списка 100, подразделяются на три типа: операция добавления элемента списка, операция логического удаления элемента списка и операция удаления элемента списка.In the described method for optimizing work with linked lists, all the operations that the recording processes perform with the elements of the linked list 100 are divided into three types: the operation of adding a list item, the operation of logically deleting a list item and the operation of deleting a list item.

Операция добавления элемента списка используется процессом записи для добавления в связный список нового элемента.The operation of adding a list item is used by the writing process to add a new item to the linked list.

Операция удаления элемента списка используется процессом записи для физического удаления элемента из связного списка. При этом длина списка сокращается.The operation to delete a list item is used by the write process to physically remove the item from the linked list. The length of the list is reduced.

При выполнении операции логического удаления элемента списка длина связного списка не изменяется, так как элемент в этом случае не удаляется физически, а только помечается как удаленный. Кроме того, при выполнении операции логического удаления элемента списка данные, содержащиеся в указанном элементе, остаются неизменными. Таким образом, в случае возникновения ситуации, когда получение данных процессом чтения из элемента связного списка будет производиться в момент выполнения с указанным элементом операции логического удаления, целостность получаемых данных нарушена не будет. В случае если процесс чтения обращается к элементу списка после того, как указанный элемент был помечен как удаленный, данные, содержащиеся в элементе списка, который помечен как удаленный, процессами чтения игнорируются.When performing the operation of logical deletion of a list item, the length of the linked list does not change, since the item in this case is not physically deleted, but only marked as deleted. In addition, when performing a logical deletion operation on a list item, the data contained in the specified item remains unchanged. Thus, in the event of a situation when the data is received by the reading process from the linked list item at the time the logical deletion operation is performed with the specified item, the integrity of the received data will not be violated. If the reading process accesses the list item after the specified item has been marked as deleted, the data contained in the list item that is marked as deleted is ignored by the reading processes.

На Фиг.4 показана структурная схема способа работы процесса чтения в способе оптимизации работы со связными списками. На этапе 410 процесс чтения начинает работу со связным списком 100. При этом значение активного в этот момент счетчика увеличивается на единицу на этапе 420. На этапе 430 процесс чтения получает от устройства хранения количества элементов списка 340 количество элементов списка, которое ему необходимо пройти, после чего обращается к первому элементу списка на этапе 440. На этапе 450 процесс чтения проверяет, не помечен ли элемент, к которому он обращается, как удаленный. В случае если элемент не помечен как удаленный, на этапе 460 производится чтение его данных, в противном случае на этапе 465 данные, содержащиеся в элементе, процессом чтения игнорируются. После этого процесс чтения на этапе 470 проверяет, не равно ли количество пройденных им элементов связного списка 100 полученному на этапе 430 количеству элементов. Если указанное равенство имеет место, процесс чтения завершает работу со списком на этапе 485, при этом значение активного на момент начала работы процесса чтения со списком счетчика уменьшается на единицу на этапе 490. В противном случае процесс чтения по ссылке первого элемента переходит к следующему элементу связного списка 100 на этапе 480. Этапы 450, 460, 465, 470 и 480 повторяются для последующих элементов связного списка 100 до тех пор, пока указанное равенство не будет достигнуто.Figure 4 shows a structural diagram of the method of operation of the reading process in a method of optimizing the work with linked lists. At step 410, the reading process starts working with the linked list 100. At the same time, the value of the active counter at that moment increases by one at step 420. At step 430, the reading process receives from the storage device the number of list items 340 the number of list items that it needs to go through, after which refers to the first element of the list at step 440. At step 450, the reading process checks to see if the element to which it refers is marked as deleted. If the element is not marked as deleted, at step 460 its data is read, otherwise at 465, the data contained in the element is ignored by the reading process. After that, the reading process at step 470 checks to see if the number of elements passed by it in the linked list 100 is equal to the number of elements obtained at step 430. If this equality holds, the reading process terminates with the list at step 485, while the value of the reading process with the list of the counter active at the time of the beginning of the work decreases by one at step 490. Otherwise, the reading process goes to the next connected element by reference of the first element list 100 at step 480. Steps 450, 460, 465, 470 and 480 are repeated for subsequent elements of linked list 100 until the equality is reached.

На Фиг.5 показана структурная схема способа работы процесса записи в способе оптимизации работы со списками при выполнении операции логического удаления элемента списка. На этапе 510 процесс записи начинает работу со связным списком 100 и производит поиск элемента списка, который необходимо удалить логически, на этапе 520. В случае если элемент не найден, процесс записи завершает работу со связным списком 100 на этапе 540. В случае если элемент найден, прежде чем завершить работу со связным списком 100 на этапе 540, процесс записи производит пометку найденного элемента удаленным на этапе 530.Figure 5 shows a structural diagram of a method of operation of the recording process in a method of optimizing work with lists when performing the operation of logical deletion of a list item. At step 510, the recording process starts working with the linked list 100 and searches for the list item that must be deleted logically at step 520. If the item is not found, the recording process ends with the linked list 100 at step 540. If the item is found before completing work with linked list 100 at step 540, the recording process marks the found item deleted at step 530.

Как было указано выше, операция логического удаления элемента связного списка не влияет на целостность получаемых процессом чтения данных, так как при выполнении данной операции процесс записи не осуществляет изменение содержащихся в элементе данных.As mentioned above, the operation of logical deletion of a linked list item does not affect the integrity of the data obtained by the reading process, since when performing this operation, the recording process does not modify the data contained in the item.

На Фиг.6 показана структурная схема способа работы процесса записи в способе оптимизации работы со списками при выполнении операции добавления элемента списка. При выполнении данной операции новый элемент списка может быть добавлен в конец списка, при этом длина списка увеличится, либо вместо логически удаленного элемента, в случае если такой элемент присутствует в списке. Добавление нового элемента вместо логически удаленного обеспечивает более эффективное использование пространства списка, что в свою очередь увеличивает скорость выполнения операций поиска элементов списка.Figure 6 shows a structural diagram of a method of operation of the recording process in a method of optimizing work with lists when performing the operation of adding a list item. When performing this operation, a new list item can be added to the end of the list, while the length of the list will increase, or instead of a logically deleted item, if such an item is present in the list. Adding a new element instead of a logically deleted one provides more efficient use of list space, which in turn increases the speed of search operations for list items.

На этапе 610 процесс записи начинает работу со связным списком 100, после чего, на этапе 620, определяет, присутствует ли в списке логически удаленный элемент. В случае если логически удаленный элемент в списке присутствует, процесс записи копирует данные нового элемента в логически удаленный элемент на этапе 630, после чего снимает с элемента пометку удаленным на этапе 640 и на этапе 670 завершает работу со списком. Таким образом, все процессы чтения, которые вслед за этим начнут работу со списком, увидят новый элемент вместо логически удаленного. В случае если на этапе 620 логически удаленный элемент в списке 100 не обнаружен, процесс записи добавляет новый элемент в конец списка на этапе 650, после чего на этапе 660 увеличивает на единицу значение, хранящееся в устройстве хранения количества элементов списка 340, и на этапе 670 завершает работу со списком. Таким образом, все процессы чтения, которые вслед за этим начнут работу со списком, увидят новый элемент, так как равенство между количеством пройденных процессом чтения элементов списка 100 станет равно значению, хранящемуся в устройстве хранения количества элементов списка 340, только после прочтения нового элемента.At step 610, the recording process starts working with the linked list 100, after which, at step 620, it determines whether a logically deleted item is present in the list. If a logically deleted element is present in the list, the recording process copies the data of the new element to the logically deleted element at step 630, after which it removes the mark deleted from the element at step 640 and completes work with the list at step 670. Thus, all reading processes, which will then begin working with the list, will see a new element instead of a logically deleted one. If at step 620 no logically deleted item was found in the list 100, the recording process adds a new item to the end of the list at step 650, after which at step 660 it increases by one the value stored in the storage device for the number of items in the list 340, and at step 670 finishes work with the list. Thus, all the reading processes, which will then begin working with the list, will see a new element, since the equality between the number of elements passed through the reading process of the list 100 will become equal to the value stored in the storage device for the number of elements in the list 340, only after reading the new element.

На Фиг.7 показана структурная схема способа работы процесса записи в способе оптимизации работы со списками при выполнении операции удаления элемента списка. Так как в указанной операции элемент удаляется физически, в рассматриваемом алгоритме исключена вероятность получения процессом чтения нецелостных данных. На этапе 710 процесс записи начинает работу со связным списком 100 и на этапе 720 производит поиск элемента списка, который необходимо удалить. Указанный алгоритм рассматривается для случая, когда элемент, который необходимо удалить, найден в списке. В случае если элемент найден не будет, процесс записи завершает работу со связным списком 100. После того как элемент, который необходимо удалить, найден, процесс записи на этапе 730 определяет, является ли данный элемент последним в списке. В случае если элемент, который необходимо удалить, является последним в списке, процесс записи на этапе 735 уменьшает на единицу значение, хранящееся в устройстве хранения количества элементов списка 340, и на этапе 745 переключает активный счетчик с помощью устройства переключения активного счетчика 310. Все процессы чтения, которые вслед за этим начнут работу со списком, не увидят элемента, который необходимо удалить, так как равенство между количеством пройденных процессом чтения элементов станет равно значению, хранящемуся в устройстве хранения количества элементов списка 340, при прохождении процессом чтения предпоследнего элемента списка. Элемент, который необходимо удалить, может быть виден только тем процессам чтения, которые начали работу со списком до уменьшения на единицу значения устройства 340 на этапе 735 и, следовательно, до переключения активного счетчика на этапе 745. Так как указанные процессы чтения начинали работу со списком до переключения активного счетчика на этапе 745, при завершении их работы со списком будет уменьшаться на единицу счетчик, который после переключения активного счетчика на этапе 745 стал неактивным. Значение «ноль» указанного счетчика будет свидетельствовать о том, что все процессы чтения, которым мог быть виден удаляемый элемент, закончили работу со списком. Поэтому для того, чтобы избежать случая получения процессом чтения нецелостных данных, прежде чем удалить последний элемент списка процессу записи необходимо удостовериться в том, что значение неактивного счетчика равно нулю. С этой целью на этапе 755 процесс записи определяет, является ли значение неактивного счетчика равным нулю. В случае если значение неактивного счетчика не равно нулю, процесс записи на этапе 785 ожидает до тех пор, пока это значение не станет равным нулю. В случае если значение неактивного счетчика равно нулю, процесс записи удаляет последний элемент списка на этапе 765 и завершает работу со списком на этапе 775.Fig. 7 shows a structural diagram of a method of operating a recording process in a method for optimizing work with lists when performing a delete operation of a list item. Since in the indicated operation the element is physically deleted, the probability of obtaining non-integral data by the reading process is excluded in the considered algorithm. At step 710, the recording process starts working with the linked list 100 and, at step 720, searches for the list item to be deleted. The specified algorithm is considered for the case when the element to be deleted is found in the list. If the item cannot be found, the recording process ends with the linked list 100. After the item to be deleted is found, the recording process determines at step 730 whether this item is the last in the list. If the item to be deleted is the last in the list, the recording process in step 735 decreases by one the value stored in the storage device of the number of items in the list 340, and in step 745 switches the active counter using the switching device of the active counter 310. All processes readings, which after that start working with the list, will not see the element that needs to be deleted, since the equality between the number of elements passed by the reading process will become equal to the value stored in the device neniya number list 340 elements during the passage of the penultimate read list element process. The element that needs to be deleted can be visible only to those reading processes that started working with the list until the value of the device 340 decreased by one at step 735 and, therefore, before switching the active counter at step 745. Since these reading processes started working with the list before switching the active counter at step 745, upon completion of their work with the list, the counter will decrease by one, which after switching the active counter at step 745 will become inactive. The value “zero” of the specified counter will indicate that all reading processes that could be visible to the deleted item have finished working with the list. Therefore, in order to avoid the case when the reading process receives non-integral data, before deleting the last element of the list, the recording process needs to make sure that the value of the inactive counter is zero. To this end, at step 755, the recording process determines whether the value of the inactive counter is zero. If the value of the inactive counter is not equal to zero, the recording process at step 785 waits until this value becomes equal to zero. If the value of the inactive counter is equal to zero, the recording process deletes the last element of the list at step 765 and completes the work with the list at step 775.

В случае если элемент, который необходимо удалить, не является последним в списке, процесс записи помечает данный элемент как удаленный на этапе 740 по алгоритму для операции логического удаления, описанному выше. После этого, на этапе 750, процесс записи производит копирование данных из последующего элемента в элемент, который на этапе 740 был помечен как удаленный. Далее процесс записи на этапе 760 снимает пометку удаленным с элемента, в который на этапе 750 были скопированы данные из последующего элемента, а сам последующий элемент помечает как удаленный на этапе 770. Таким образом, процесс записи меняет местами элемент, который необходимо удалить, с последующим элементом. То есть элемент, который необходимо удалить, перемещается к концу списка. Этапы 740, 750, 760 и 770 повторяются до тех пор, пока элемент, который необходимо удалить, не станет последним в списке, после чего данный элемент удаляется согласно этапам 735, 745, 755, 765, 775 и 785 описываемого алгоритма.If the item to be deleted is not the last in the list, the recording process marks this item as deleted at step 740 according to the algorithm for the logical delete operation described above. After that, at step 750, the recording process copies data from the subsequent element to the element, which at step 740 was marked as deleted. Next, the recording process at step 760 removes the mark deleted from the element into which data from the subsequent element was copied at step 750, and the subsequent element itself is marked as deleted at step 770. Thus, the recording process swaps the element that needs to be deleted, followed by an element. That is, the item to be deleted moves to the end of the list. Steps 740, 750, 760 and 770 are repeated until the element to be deleted becomes the last in the list, after which this element is deleted according to steps 735, 745, 755, 765, 775 and 785 of the described algorithm.

Стоит также отметить, что этапы 745, 755 и 785, на которых происходит переключение активного счетчика, проверка значения неактивного счетчика и ожидание момента времени, когда данное значение станет равным нулю, могут осуществляться и для других операций изменения связного списка.It is also worth noting that steps 745, 755 and 785, in which the active counter is switched, checking the value of the inactive counter and waiting for the time when this value becomes zero, can be performed for other operations of changing the linked list.

В заключение следует отметить, что приведенные в описании сведения являются примерами, которые не ограничивают объем настоящего изобретения, определенного формулой. Специалисту в данной области становится понятным, что могут существовать и другие варианты осуществления настоящего изобретения, согласующиеся с сущностью и объемом настоящего изобретения.In conclusion, it should be noted that the information provided in the description are examples that do not limit the scope of the present invention defined by the claims. One skilled in the art will recognize that there may be other embodiments of the present invention consistent with the spirit and scope of the present invention.

Claims (6)

1. Способ предоставления процессам чтения непрерывного доступа к связному списку, который содержит один процесс записи и, по крайней мере, один процесс чтения, и в котором при удалении последнего элемента списка:
все процессы чтения без ожидания получают доступ к списку и разделяются на процессы чтения, которые начали работу со списком до того, как процесс записи перешел к последнему элементу списка, и на процессы чтения, которые начали работу со списком после того, как процесс записи перешел к последнему элементу списка, при этом:
а) процессы чтения, которые начали работу со списком до того, как процесс записи перешел к последнему элементу списка, выполняются для количества элементов списка, содержащих последний элемент;
б) процессы чтения, которые начали работу со списком после того, как процесс записи перешел к последнему элементу списка, выполняются для количества элементов списка, не содержащих последний элемент;
при этом процесс записи удаляет последний элемент списка только после того, как все процессы чтения, которые начали работу со списком до того, как процесс записи перешел к последнему элементу, закончили работу со списком.
1. A method for providing reading processes with continuous access to a linked list that contains one write process and at least one read process, and in which, when the last element of the list is deleted:
all read processes without waiting gain access to the list and are divided into reading processes that started working with the list before the writing process went to the last element of the list, and reading processes that started working with the list after the writing process went to the last element of the list, with:
a) the reading processes that started working with the list before the writing process moved to the last element of the list are performed for the number of list elements containing the last element;
b) the reading processes that started working with the list after the writing process has moved to the last element of the list, are performed for the number of elements in the list that do not contain the last element;
at the same time, the writing process deletes the last element of the list only after all the reading processes that started working with the list before the writing process moved to the last element finished working with the list.
2. Способ по п.1, в котором процесс записи перемещает элемент, который необходимо удалить, в конец списка в случае, если элемент, который необходимо удалить, не является последним в списке.2. The method of claim 1, wherein the recording process moves the item to be deleted to the end of the list if the item to be deleted is not the last in the list. 3. Способ по п.1, в котором процесс записи также производит логическое удаление элемента списка путем пометки элемента удаленным, при этом данные логически удаленного элемента списка игнорируются процессом чтения, и элемент остается в списке.3. The method according to claim 1, in which the recording process also logically deletes the list item by marking the item deleted, while the data of the logically deleted list item is ignored by the reading process, and the item remains in the list. 4. Способ предоставления процессам чтения непрерывного доступа к связному списку, который содержит один процесс записи и, по крайней мере, один процесс чтения, и в котором при добавлении нового элемента списка:
все процессы чтения без ожидания получают доступ к списку и разделяются на процессы чтения, которые начали работу со списком до добавления нового элемента, и на процессы чтения, которые начали работу со списком после добавления нового элемента, при этом:
а) процессы чтения, которые начали работу со списком до добавления нового элемента, выполняются для количества элементов списка, не содержащих добавляемый элемент;
б) процессы чтения, которые начали работу со списком после добавления нового элемента, выполняются для количества элементов списка, содержащих добавленный элемент.
4. A method for providing reading processes with continuous access to a linked list that contains one writing process and at least one reading process, and in which when adding a new list item:
all read processes without waiting gain access to the list and are divided into reading processes that started working with the list before adding a new element, and reading processes that started working with the list after adding a new element, while:
a) the reading processes that started working with the list before adding a new item are performed for the number of list items that do not contain the item to be added;
b) the reading processes that started working with the list after adding a new item are performed for the number of list items containing the added item.
5. Способ по п.4, в котором процесс записи добавляет новый элемент в конец списка, в случае, если в списке нет логически удаленного элемента.5. The method according to claim 4, in which the recording process adds a new element to the end of the list, if the list does not have a logically deleted element. 6. Способ по п.4, в котором процесс записи добавляет новый элемент путем копирования данных нового элемента в логически удаленный элемент и снятия с логически удаленного элемента пометки удаленным, в случае если в списке присутствует логически удаленный элемент. 6. The method according to claim 4, in which the recording process adds a new element by copying the data of the new element to the logically remote element and removing the tag from the logically deleted element deleted if the logically deleted element is present in the list.
RU2011126322/08A 2011-06-28 2011-06-28 Method of optimising work with linked lists RU2480819C2 (en)

Priority Applications (1)

Application Number Priority Date Filing Date Title
RU2011126322/08A RU2480819C2 (en) 2011-06-28 2011-06-28 Method of optimising work with linked lists

Applications Claiming Priority (1)

Application Number Priority Date Filing Date Title
RU2011126322/08A RU2480819C2 (en) 2011-06-28 2011-06-28 Method of optimising work with linked lists

Publications (2)

Publication Number Publication Date
RU2011126322A RU2011126322A (en) 2013-01-10
RU2480819C2 true RU2480819C2 (en) 2013-04-27

Family

ID=48795120

Family Applications (1)

Application Number Title Priority Date Filing Date
RU2011126322/08A RU2480819C2 (en) 2011-06-28 2011-06-28 Method of optimising work with linked lists

Country Status (1)

Country Link
RU (1) RU2480819C2 (en)

Citations (5)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
EA006038B1 (en) * 2001-11-01 2005-08-25 Верисайн, Инк. Transactional memory manager
US7000234B1 (en) * 2000-01-20 2006-02-14 Sun Microsystems, Inc. Maintaining a double-ended queue as a linked-list with sentinel nodes and delete flags with concurrent non-blocking insert and remove operations using a double compare-and-swap primitive
US7117502B1 (en) * 2000-11-10 2006-10-03 Sun Microsystems, Inc. Linked-list implementation of a data structure with concurrent non-blocking insert and remove operations
US7533138B1 (en) * 2004-04-07 2009-05-12 Sun Microsystems, Inc. Practical lock-free doubly-linked list
US7536428B2 (en) * 2006-06-23 2009-05-19 Microsoft Corporation Concurrent read and write access to a linked list where write process updates the linked list by swapping updated version of the linked list with internal list

Patent Citations (5)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
US7000234B1 (en) * 2000-01-20 2006-02-14 Sun Microsystems, Inc. Maintaining a double-ended queue as a linked-list with sentinel nodes and delete flags with concurrent non-blocking insert and remove operations using a double compare-and-swap primitive
US7117502B1 (en) * 2000-11-10 2006-10-03 Sun Microsystems, Inc. Linked-list implementation of a data structure with concurrent non-blocking insert and remove operations
EA006038B1 (en) * 2001-11-01 2005-08-25 Верисайн, Инк. Transactional memory manager
US7533138B1 (en) * 2004-04-07 2009-05-12 Sun Microsystems, Inc. Practical lock-free doubly-linked list
US7536428B2 (en) * 2006-06-23 2009-05-19 Microsoft Corporation Concurrent read and write access to a linked list where write process updates the linked list by swapping updated version of the linked list with internal list

Also Published As

Publication number Publication date
RU2011126322A (en) 2013-01-10

Similar Documents

Publication Publication Date Title
US9846645B1 (en) Managing objects stored in memory
US9881041B2 (en) Multiple RID spaces in a delta-store-based database to support long running transactions
US8108696B2 (en) Optimizing non-preemptible read-copy update for low-power usage by avoiding unnecessary wakeups
US9396226B2 (en) Highly scalable tree-based trylock
US20150205646A1 (en) Context aware synchronization
JP5797855B2 (en) Virus scanning method and virus scanning apparatus
FI3382551T3 (en) Distributed hardware tracing
US20160147806A1 (en) Versioned bloom filter
CN106155839B (en) A kind of method and apparatus for Backup Data
US11366788B2 (en) Parallel pipelined processing for snapshot data deletion
US20150277966A1 (en) Transaction system
WO2016070529A1 (en) Method and device for achieving duplicated data deletion
US20160011789A1 (en) Storage control apparatus and control method of storage control apparatus
WO2015183316A1 (en) Partially sorted log archive
CN112306699A (en) Method and device for accessing critical resource, computer equipment and readable storage medium
US20120059997A1 (en) Apparatus and method for detecting data race
US20140379995A1 (en) Semiconductor device for controlling prefetch operation
US20140320498A1 (en) Terminal device, information processing method, and computer program product
CN114327642A (en) Data read-write control method and electronic equipment
US11809733B2 (en) Systems and methods for object migration in storage devices
JP2018132948A (en) Loading program, loading method, and information processing device
RU2480819C2 (en) Method of optimising work with linked lists
WO2013049022A1 (en) Extreme large space allocation
WO2015057962A1 (en) Concurrently accessing memory
CN112068948B (en) Data hashing method, readable storage medium and electronic device