임베디드/[ RTOS ]

[ RTOS ] 04. ThreadX의 Counting Semaphores

kim.svadoz 2021. 4. 1. 09:59
728x90
반응형

Counting Semaphores

ThreadX provides 32-bit counting semaphores that range in value between 0 and 4,294,967,295. There are two operations for counting semaphores: tx_semaphore_get and tx_semaphore_put. The get operation decreases the semaphore by one. If the semaphore is 0, the get operation is not successful. The inverse of the get operation is the put operation. It increases the semaphore by one.

Each counting semaphore is a public resource. ThreadX places no constraints on how counting semaphores are used.

Counting semaphores are typically used for mutual exclusion. However, counting semaphores can also be used as a method for event notification.

ThreadX는 0에서 4,294,967,295 사이의 값 범위를 갖는 32 비트 카운팅 세마포어를 제공합니다. 세마포를 계산하는 작업에는 tx_semaphore_get과 tx_semaphore_put의 두 가지 작업이 있습니다.

get 작업은 세마포어를 하나씩 줄입니다. 세마포어가 0이면 가져 오기 작업이 성공하지 못합니다. get 작업의 역은 put 작업입니다. 세마포어를 하나씩 증가시킵니다.

각 계수 세마포어는 공용 리소스입니다. ThreadX는 세마포어를 계산하는 방법에 제한을 두지 않습니다.

세마포 계산은 일반적으로 상호 배제에 사용됩니다. 그러나 카운트 세마포어는 이벤트 알림을위한 방법으로도 사용할 수 있습니다.

  • Mutual Exclusion

Mutual exclusion pertains to controlling the access of threads to certain application areas (also called critical sections or application resources). When used for mutual exclusion, the “current count” of a semaphore represents the total number of threads that are allowed access. In most cases, counting semaphores used for mutual exclusion will have an initial value of 1, meaning that only one thread can access the associated resource at a time. Counting semaphores that only have values of 0 or 1 are commonly called binary semaphores.

If a binary semaphore is being used, the user must prevent the same thread from performing a get operation on a semaphore it already owns. A second get would be unsuccessful and could cause indefinite suspension of the calling thread and permanent unavailability of the resource.

상호 배제는 특정 애플리케이션 영역 (중요 섹션 또는 애플리케이션 자원이라고도 함)에 대한 스레드 액세스 제어와 관련이 있습니다.

상호 배제에 사용되는 경우 세마포어의 "현재 수"는 액세스가 허용 된 총 스레드 수를 나타냅니다. 대부분의 경우 상호 배제에 사용되는 계산 세마포어의 초기 값은 1입니다. 즉, 한 번에 하나의 스레드 만 연결된 리소스에 액세스 할 수 있습니다. 값이 0 또는 1 인 세마포를 계산하는 것을 일반적으로 이진 세마포라고합니다.

바이너리 세마포어를 사용하는 경우 사용자는 동일한 스레드가 이미 소유 한 세마포어에 대해 get 작업을 수행하지 못하도록해야합니다. 두 번째 가져 오기는 실패하고 호출 스레드가 무기한 중단되고 리소스를 영구적으로 사용할 수 없게됩니다.

  • Event Notification

It is also possible to use counting semaphores as event notification, in a producer-consumer fashion. The consumer attempts to get the counting semaphore while the producer increases the semaphore whenever something is available. Such semaphores usually have an initial value of 0 and won’t increase until the producer has something ready for the consumer.

생산자-소비자 방식으로 이벤트 알림으로 카운팅 세마포어를 사용할 수도 있습니다.

소비자는 카운팅 세마포어를 얻으려고 시도하는 반면 생산자는 무언가를 사용할 수있을 때마다 세마포어를 증가시킵니다. 이러한 세마포어는 일반적으로 초기 값이 0이며 생산자가 소비자를 위해 준비 할 때까지 증가하지 않습니다.

  • Creating Counting Semaphores

Counting semaphores are created either during initialization or during run-time by application threads. The initial count of the semaphore is specified during creation. There are no limits on the number of counting semaphores in an application.

카운팅 세마포어는 초기화 중에 또는 런타임 중에 애플리케이션 스레드에 의해 생성됩니다. 세마포어의 초기 개수는 생성 중에 지정됩니다. 응용 프로그램에서 세마포 수를 세는 데 제한이 없습니다.

  • Thread Suspension

Application threads can suspend while attempting to perform a get operation on a semaphore with a current count of 0.

Once a put operation is performed, the suspended thread’s get operation is performed and the thread is resumed. If multiple threads are suspended on the same counting semaphore, they are resumed in the same order they were suspended (FIFO).

However, priority resumption is also possible if the application calls tx_semaphore_prioritize prior to the semaphore put call that lifts thread suspension. The semaphore prioritize service places the highest priority thread at the front of the suspension list, while leaving all other suspended threads in the same FIFO order.

현재 개수가 0 인 세마포어에서 가져 오기 작업을 수행하는 동안 응용 프로그램 스레드가 일시 중지 될 수 있습니다.

넣기 작업이 수행되면 일시 중단 된 스레드의 가져 오기 작업이 수행되고 스레드가 다시 시작됩니다. 여러 스레드가 동일한 계산 세마포어에서 일시 중단 된 경우 일시 중단 된 동일한 순서 (FIFO)로 다시 시작됩니다.

그러나 스레드 일시 중단을 해제하는 세마포 풋 호출 이전에 애플리케이션이 tx_semaphore_prioritize를 호출하는 경우에도 우선 순위 재개가 가능합니다. 세마포어 우선 순위 지정 서비스는 가장 높은 우선 순위 스레드를 일시 중단 목록 앞에 배치하고 다른 모든 일시 중단 된 스레드는 동일한 FIFO 순서로 둡니다.

  • Semaphore Control Block TX_SEMAPHORE

The characteristics of each counting semaphore are found in its control block. It contains interesting information such as the current semaphore count. This structure is defined in the tx_api.h file.

Semaphore control blocks can be located anywhere in memory, but it is most common to make the control block a global structure by defining it outside the scope of any function.

각 계수 세마포어의 특성은 제어 블록에서 찾을 수 있습니다. 현재 세마포어 수와 같은 흥미로운 정보가 포함되어 있습니다. 이 구조는 tx_api.h 파일에 정의되어 있습니다.

세마포어 제어 블록은 메모리의 어느 곳에 나 위치 할 수 있지만 제어 블록을 모든 기능의 범위 밖에서 정의하여 전역 구조로 만드는 것이 가장 일반적입니다.

  • Deadly Embrace (치명적인 포옹?)

One of the most interesting and dangerous pitfalls associated with semaphores used for mutual exclusion is the deadly embrace. A deadly embrace, or deadlock, is a condition where two or more threads are suspended indefinitely while attempting to get semaphores already owned by other threads.

This condition is best illustrated by a two thread, two semaphore example. Suppose the first thread owns the first semaphore and the second thread owns the second semaphore. If the first thread attempts to get the second semaphore and at the same time the second thread attempts to get the first semaphore, both threads enter a deadlock condition. In addition, if these threads stay suspended forever, their associated resources are locked-out forever as well. Figure 8 on page 71 illustrates this example.

상호 배제에 사용되는 세마포어와 관련된 가장 흥미롭고 위험한 함정 중 하나는 치명적인 포옹입니다. 치명적인 포괄 또는 교착 상태는 다른 스레드가 이미 소유 한 세마포어를 가져 오려고 시도하는 동안 두 개 이상의 스레드가 무기한 일시 중단되는 상태입니다.

이 조건은 두 개의 스레드, 두 개의 세마포어 예에서 가장 잘 설명됩니다. 첫 번째 스레드가 첫 번째 세마포를 소유하고 두 번째 스레드가 두 번째 세마포를 소유한다고 가정합니다. 첫 번째 스레드가 두 번째 세마포어를 얻으려고 시도하고 동시에 두 번째 스레드가 첫 번째 세마포어를 얻으려고하면 두 스레드가 모두 교착 상태에 들어갑니다. 또한 이러한 스레드가 영구적으로 일시 중단 된 상태로 유지되면 관련 리소스도 영구적으로 잠 깁니다. 71 페이지의 그림 8은이 예를 보여줍니다.

107336816-eb7be400-6afc-11eb-96bf-fa8e871a0fd5

How are deadly embraces avoided? Prevention in the application is the best method for real-time systems. This amounts to placing certain restrictions on how threads obtain semaphores. Deadly embraces are avoided if threads can only have one semaphore at a time. Alternatively, threads can own multiple semaphores if they all gather them in the same order. In the previous example, if the first and second thread obtain the first and second semaphore in order, the deadly embrace is prevented.

It is also possible to use the suspension time-out associated with the get operation to recover from a deadly embrace.

치명적인 포옹은 어떻게 피합니까?

응용 프로그램의 예방은 실시간 시스템을위한 최선의 방법입니다. 이것은 스레드가 세마포어를 얻는 방법에 특정 제한을 두는 것과 같습니다.

스레드가 한 번에 하나의 세마포어 만 가질 수있는 경우 치명적인 포용이 방지됩니다.

또는 스레드가 모두 동일한 순서로 수집하는 경우 여러 세마포를 소유 할 수 있습니다. 앞의 예에서 첫 번째와 두 번째 스레드가 첫 번째와 두 번째 세마포어를 순서대로 획득하면 치명적인 포옹이 방지됩니다.

치명적인 포옹에서 회복하기 위해 get 작업과 관련된 중단 시간 제한을 사용할 수도 있습니다.

  • Priority Inversion

Another pitfall associated with mutual exclusion semaphores is priority inversion. This topic is discussed more fully in “Thread Priority Pitfalls” on page 62.

The basic problem results from a situation where a lower-priority thread has a semaphore that a higherpriority thread needs. This in itself is normal. However, threads with priorities in between them may cause the priority inversion to last a nondeterministic amount of time. This can be handled through careful selection of thread priorities, using preemption- thresholds, and temporarily raising the priority of the thread that owns the resource to that of the high-priority thread.

상호 배제 세마포어와 관련된 또 다른 함정은 우선 순위 반전입니다. 이 주제는 62 페이지의 "스레드 우선 순위 함정"에서 자세히 설명합니다.

기본적인 문제는 우선 순위가 낮은 스레드가 높은 우선 순위 스레드가 필요로하는 세마포어를 갖는 상황에서 발생합니다. 이것은 그 자체로 정상입니다. 그러나 그 사이에 우선 순위가있는 스레드는 우선 순위 반전이 비 결정적 시간 동안 지속되도록 할 수 있습니다. 이것은 스레드 우선 순위를 신중하게 선택하고, 선점 임계 값을 사용하고, 리소스를 소유 한 스레드의 우선 순위를 높은 우선 순위 스레드의 우선 순위로 일시적으로 올려서 처리 할 수 있습니다.

728x90
반응형