Pipelining is frequently associated with the processing of streaming data, like images taken from a camera that monitors objects on a conveyor belt (compare figure 2.4). In this case, the image of object 3 may be acquired at the same time as the image of object 2 is processed and at the same time as the image processing results of object 1 are evaluated.
The individual processing steps, e.g., image acquisition, image processing, and result evaluation, are executed by different stages that are connected by message queues such that the output of one stage is the input of the next one (see figure 2.5). Thus, a pipeline is composed of (typically) multiple producer/consumer pairs.
Figure 2.5: Simple pipeline that consists of the three stages image acquisition, image processing, and result evaluation.
The pipeline in figure 2.5 consists of three stages, which are connected by two message queues. All three stages run in separate threads that run in parallel. The image acquisition stage acquires the images. Each image is put into a message, which then is enqueued into the message queue 1. The message queues act as FIFO (first in, first out) buffers, which connect the consecutive stages. If the image processing stage is ready to process the next image and as soon as there is a message available in message queue 1, the image processing stage dequeues a message from the head of message queue 1. It processes the image that is contained in the message and adds the processing results to the message. Then it enqueues this message to message queue 2. Finally, the result evaluation stage dequeues the message from the head of message queue 2 and evaluates the results, e.g., by initiating some action like blowing-out defective products.
As the threads run in parallel, the result evaluation for the first image may be executed parallel to the processing of the second image and parallel to the acquisition of the third image. Typically, the processing time of the different stages is unequal. For example, in figure 2.6, the image processing stage takes twice as long as the result evaluation stage.
The cycle time of a pipeline is the time between the completion of consecutive tasks. The throughput of a pipeline is the inverse of its cycle time. Note that the throughput of a pipeline is limited by the throughput of its slowest stage.
Because the individual stages of a pipeline are executed in parallel, its throughput is typically higher than the throughput of a program that executes the stages sequentially (see figure 2.7).
Example Implementation of the Pipeline
The implementation of a pipeline follows the pattern:
The HDevelop example program hdevelop/System/Multithreading/pipeline_one_thread_per_stage.hdev shows an implementation of a pipeline similar to the one referred to in figure 2.5 and figure 2.6.
First, the functionality of the different stages has to be put into individual procedures. Here, the three procedures acquire_images, process_images, and evaluate_results are used. The data that must be passed from one stage to the next stage will be passed through message queues. As we have three stages, we need two message queues to connect theses stages. They are created with the operators create_message_queue:
create_message_queue (QueueOriginalImage) create_message_queue (QueueImageProcessingResult)
Typically, the size of the message queues should be limited to control the memory usage of the program. This is done by the following calls:
MessageQueueMaxMessageNum := 200
set_message_queue_param (QueueOriginalImage, 'max_message_num', \
MessageQueueMaxMessageNum)
set_message_queue_param (QueueImageProcessingResult, 'max_message_num', \
MessageQueueMaxMessageNum)
Note that the size of the message queues should be chosen large enough to allow them to handle short-term peak loads. If, e.g., for a short period of time, the images are acquired faster than they can be processed, they will be buffered in the message queue.
To be able to stop the image acquisition, we use an event that is monitored inside the procedure acquire_images.
create_event ('', '', StopAcq)
Furthermore, we propagate the information that the image acquisition has been stopped with a respective message. This message is created by the image acquisition stage as soon as the image acquisition is stopped. It indicates that no further messages will follow. To identify this message, we define a particular message key:
TerminationKey := 'terminate'
Then, we can start the procedures in individual threads:
par_start<AcquisitionThread> : acquire_images (MeanAcquisitionInterval, \
StopAcq, TerminationKey, \
QueueOriginalImage)
par_start<ImageProcessingThread> : process_images (QueueOriginalImage, \
NumAOPThreadsForImageProcessing, \
TerminationKey, \
QueueImageProcessingResult)
par_start<ResultEvaluationThread> : evaluate_results (QueueImageProcessingResult, \
TerminationKey, \
WindowHandle)
In the example program, the pipeline runs just a few seconds and is then terminated by signaling the event StopAcq:
signal_event (StopAcq)
Now, the image acquisition stage, which monitors the state of the event StopAcq, terminates and sends a message to the subsequent stages, which will terminate themselves as soon as they evaluate this message.
Finally, we must wait until all threads are finished.
par_join ([AcquisitionThread,ImageProcessingThread,ResultEvaluationThread])
Example Implementation of the Image Acquisition Stage
The implementation of the first stage (here represented by the procedure acquire_images) follows the pattern:
The image acquisition stage acquires images in a loop, which is not exited until either the image acquisition is terminated by signaling the termination event or the message queue that connects the image acquisition stage with the image processing stage reaches its limit.
In our example, the image acquisition is simulated by picking a random image from an array of pre-read images and waiting some time to simulate a realistic time interval between the acquisition of two images. In real applications, these two lines must be replaced to acquire real images.
repeat
wait_to_simulate_non_trivial_acquisition_time (MeanAcquisitionInterval, \
ImageId, \
LastAcquisitionTime, \
LastAcquisitionTime)
acquire_random_image (Images, Image)
For each image, we create a message and store the image together with an image ID and a time stamp in this message.
create_message (MessageImg)
set_message_obj (Image, MessageImg, 'image')
set_message_tuple (MessageImg, 'image_id', ImageId)
set_message_tuple (MessageImg, 'acquisition_time', AcquisitionTime)
Finally, the message is enqueued into the message queue that connects the image acquisition stage with the image processing stage. Because the size of our message queues is limited, we must take care of the case that the message queue already contains its maximally allowed number of messages. For this, we use a procedure that can be configured to handle this case in the desired way.
enqueue_message_to_limited_queue (MessageImg, QueueOut, \
'throw_exception')
Here, we want to throw an exception if the message queue is at its limit. In real applications, this case must be handled individually and with care. It indicates that one of the following stages cannot handle the images in the required speed. Because the reduction of the image acquisition rate is most often not the desired solution, the speed of the pipeline must be increased. See section “Speedup the Pipeline” for possible ways to speedup the pipeline.
Finally, we check if the image acquisition should be terminated by checking the state of the event StopAcq. As long as this event is not signaled, the image acquisition stage continues to acquire images.
try_wait_event (StopAcq, Busy) until (not Busy)
If the event StopAcq is signaled, the image acquisition loop will be left and the complete pipeline can be terminated. To do this in a way that all acquired images are still being processed, we create a message that contains the above defined termination key and enqueue it as the final message to the message queue. In this case, we must ensure that the message will be enqueued to the message queue. Therefore, we do not want to throw an exception if the message queue is at its limit but rather wait until the message can be enqueued.
create_message (TerminationMessage) set_message_tuple (TerminationMessage, TerminationKey, 'true') enqueue_message_to_limited_queue (TerminationMessage, QueueOut, 'wait')
Example Implementation of the Image Processing Stage
The implementation of intermediate stages (here represented by the procedure process_images) follows the pattern:
All these steps are performed inside a loop, which exits if the pipeline is terminated.
First, a message is dequeued from the input message queue:
while (1)
dequeue_message (QueueIn, [], [], MessageHandle)
Then, we check if the image acquisition was terminated and thus we have to terminate the pipeline:
get_message_param (MessageHandle, 'key_exists', TerminationKey, \
Terminate)
If we have to terminate the pipeline, the following two steps are needed:
if (Terminate)
enqueue_message_to_limited_queue (MessageHandle, QueueOut, 'wait')
break
endif
If no termination was requested, we can extract the input data (here: image) from the message, perform some action (here: image processing), and add the result (here: number of defects) to the message:
get_message_obj (Image, MessageHandle, 'image')
image_processing (Image, ImageReduced, RegionUnion, RingSize, \
PolarResolution, SmoothX, Number)
set_message_tuple (MessageHandle, 'num_defects', Number)
Finally, we enqueue the message to the output queue:
enqueue_message_to_limited_queue (MessageHandle, QueueOut, 'wait') endwhile
Here it is not necessary to throw an exception if the output queue reached its limit. We just wait until we can enqueue the message. As long as we are waiting, we cannot dequeue further messages from the input queue. If this waiting state takes too long, the input queue will reach its limit and a respective exception will be thrown by the image acquisition stage.
Example Implementation of the Result Evaluation Stage
The implementation of the final stage (here represented by the procedure evaluate_results) follows the pattern:
All these steps are performed inside a loop, which is not exited until the pipeline is terminated.
First, a message is dequeued from the input message queue:
while (1)
dequeue_message (QueueIn, [], [], MessageHandle)
Then, we check if the image acquisition was terminated and thus we have to terminate the pipeline:
get_message_param (MessageHandle, 'key_exists', TerminationKey, \
Terminate)
if (Terminate)
break
endif
endwhile
Now, we can evaluate the results. In the example, we just calculate response time, processing time, and the mean acquisition interval and visualize the data. In real applications, the results can, e.g., be used to control the elimination of defective parts.
Figure 2.8 shows the runtime behavior of the simple pipeline realized in the above described HDevelop example program. On the horizontal axis, the last 720 images are plotted. The orange line shows the acquisition interval, i.e., the time between the acquisition of two consecutive images. The acquisition interval shows some variations, which are specifically caused by the image acquisition procedure. The magenta line shows the time needed for the image processing stage, which is fairly constant over the images. The blue line shows the response time, i.e., the time between the image acquisition and the completion of the result evaluation.
|
|
| (a) | (b) |
|
| (c) |
Figure 2.8: Runtime behavior of the simple pipeline: (a) Approximately constant acquisition interval. (b) Varying acquisition interval. (c) Varying acquisition interval leading to short-term peak loads..
In figure 2.8(a), the images are acquired in approximately equal intervals of ??(Unit)6ms. Note that the image acquisition must not be faster than the slowest of the following stages of the pipeline. In our example, this stage is the image processing stage, which takes about ??(Unit)4.5ms. With the above mentioned image acquisition interval of ??(Unit)6ms, we can achieve a throughput of \nicefrac1(\Unit6ms) ≈ \Unit160\nicefrac[\textnormal]imagessec with a nearly constant response time.
In figure 2.8(b) and (c), the image acquisition interval varies over time leading to short-term peak loads. As long as the pipeline (more precisely: the slowest stage following the image acquisition stage) is fast enough, this has no negative effect on the response time. This can be seen in figure 2.8(b), where the images are always acquired slower than they are processed. Naturally, this limits the achievable throughput, because at any time, the image acquisition speed may not exceed the speed of the following stages. In this configuration of our example, only \nicefrac1(\Unit12ms) ≈ \Unit80\nicefrac[\textnormal]imagessec can be processed, again with a nearly constant response time.
If the response time is less important, for a limited period of time, the image acquisition interval can even drop below the time required to process one image (see figure 2.8(c)). As long as the image processing is faster than the image acquisition (magenta line is below the orange line), the response time lies only marginally above the image processing time. In this case, the message queues contain typically at most one message. As soon as the acquisition interval is shorter than the time required to process one image, the acquired images must be buffered in the input message queue of the image processing stage. The response time for those images, which must wait in the message queue for being processed, increases dramatically. As soon as the image acquisition is again slower than the image processing, the number of buffered images decreases and with this also the response time for newly acquired images. Note that the message queues must be configured large enough to be able to buffer the images that are waiting for being processed. In this configuration of our example, again \nicefrac1(\Unit6ms) ≈ \Unit160\nicefrac[\textnormal]imagessec can be processed, but with a response time that may be dramatically slower.
There are two possible ways to increase the speed of a pipeline:
Both approaches try to reduce the mean processing time required for the slowest stage of the pipeline, as this limits the speed of the whole pipeline.
While splitting the slowest stage into multiple stages is straightforward and probably the simpler approach, its effectiveness depends on the possibility to split the stage into pieces of approximately equal size (run time). If this is not possible, the speed of the individual stages again vary and the speed of the pipeline is suboptimal.
Figure 2.9 shows the scheduling diagram of a pipeline where the image processing stage was split into two stages. Here, it was not possible to split the image processing stage into two stages of equal size. Instead, the first part is three times larger than the second part. Compared to the simple pipeline described in figure 2.6, the cycle time of the pipeline was only slightly reduced. The stage `image processing 1' is still significantly slower than the other stages and thus limits the throughput of the pipeline.
The second approach, the parallel execution of the slowest stage on multiple threads, requires a little more implementation effort, but typically, it is easier to reach a more similar workload of the threads of this stage. Figure 2.10 shows such a pipeline, where the image processing stage runs on two threads in parallel.
Figure 2.10: Pipeline where the image processing stage runs on two threads in parallel. Note the multiplexer, which ensures that the results appear in the correct order.
Depending on the image contents, the image processing task that was started last may finish before the task that was started first.
If it is required that the results appear in the same order the tasks were started, a multiplexer must be inserted after the parallel stage into the pipeline. A multiplexer guarantees that the tasks are returned in the same order they were started. It combines the output message queues of the parallel stage into one single message queue that contains the tasks in correct order.
If the order of the results is irrelevant, e.g., if the results are written into a data base, no multiplexer is required. In those cases, the images can still be identified by their image ID.
Figure 2.11 shows the scheduling diagram for the above discussed pipeline. The image processing of the second image starts while the first image is still being processed. Compared to figure 2.6, the parallelization of the image processing stage (nearly) doubles the throughput of the pipeline.
Figure 2.11: Scheduling diagram for a pipeline where the image processing stage runs on two threads in parallel.
Example Implementation of the Pipeline
The HDevelop example program hdevelop/System/Multithreading/pipeline_multiple_threads_per_stage.hdev shows an implementation of a pipeline where the image processing stage runs on multiple threads in parallel, i.e., a pipeline which is similar to the one referred to in figure 2.10 and figure 2.11.
In the following, only the changes are described that are necessary to convert the simple pipeline as described in section “Basic Design of a Pipeline” into a pipeline that runs the image processing stage on multiple threads.
In addition to the message queue that delivers the image processing results to the result evaluation stage, we need multiple message queues that connect the image processing stage with the multiplexer:
for I := 0 to NumImageProcessingThreads - 1 by 1
create_message_queue (QueueImageProcessingResultsVector.at(I))
set_message_queue_param (QueueImageProcessingResultsVector.at(I), \
'max_message_num', MessageQueueMaxMessageNum)
endfor
convert_vector_to_tuple (QueueImageProcessingResultsVector, \
QueuesImageProcessingResult)
Instead of starting only one thread for the image processing stage, we must start multiple image processing threads as well as one multiplexer thread:
for I := 0 to NumImageProcessingThreads - 1 by 1
par_start<ImageProcessingThreadVector.at(I)> : process_images (QueueOriginalImage, \
NumAOPThreadsForImageProcessing, \
TerminationKey, \
QueueImageProcessingResultsVector.at(I))
endfor
convert_vector_to_tuple (ImageProcessingThreadVector, \
ImageProcessingThreads)
par_start<MultiplexerThread> : multiplexer (QueuesImageProcessingResult, \
'image_id', TerminationKey, \
QueueImageProcessingResult)
We must also wait for the additional threads to finish:
par_join ([AcquisitionThread,ImageProcessingThreads,MultiplexerThread, \
ResultEvaluationThread])
In order to ensure a proper termination of the pipeline, we must slightly modify the respective part of the procedure process_images. In addition to enqueuing the termination message only to the output queue, we must enqueue this message also to the input queue to inform the other threads that are running the procedure process_images, as well:
get_message_param (MessageHandle, 'key_exists', TerminationKey, \
Terminate)
if (Terminate)
enqueue_message_to_limited_queue (MessageHandle, QueueIn, 'wait')
enqueue_message_to_limited_queue (MessageHandle, QueueOut, 'wait')
break
endif
Finally, we must implement the multiplexer. The multiplexer ensures that the result evaluation stage receives the processing results in the correct sequential order. Note that the messages do not need to be sorted or reordered. Because of the fact that each input message queue is locally ordered, the multiplexer only has to look for the next message in the sequence by simultaneously monitoring the heads of all input message queues. It determines the required order of the messages from the image ID, which was set in an increasing order by the image acquisition stage.
The basic functionality of the multiplexer is provided by the following lines of code:
NumInputQueues := |QueuesIn|
LastId := -1
Buffers := gen_tuple_const(NumInputQueues,-1)
Ids := gen_tuple_const(NumInputQueues,LastId)
while (1)
for I := 0 to NumInputQueues - 1 by 1
if (Buffers[I] == -1)
dequeue_message (QueuesIn[I], [], [], MessageHandle)
get_message_tuple (MessageHandle, SortIdKey, Id)
Buffers[I] := MessageHandle
Ids[I] := Id
endif
if (Buffers[I] != -1 and Ids[I] == LastId + 1)
enqueue_message_to_limited_queue (Buffers[I], QueueOut, \
'wait')
Buffers[I] := -1
LastId := Ids[I]
endif
endfor
endwhile
The remainder of the multiplexer's code, which can be found in the HDevelop example program hdevelop/System/Multithreading/pipeline_multiple_threads_per_stage.hdev, mainly deals with its termination if the pipeline is terminated and with the — unlikely — case that some messages are missing and therefore, there are gaps in the sequence of the image IDs.
The runtime behavior of the pipeline where the image processing stage runs on two threads is shown in figure 2.12. It looks similar to that of the simple pipeline with only one thread per stage (see figure 2.8), but with the important difference that the acquisition interval may be significantly shorter. Thus, the throughput of the system was significantly increased.
|
|
| (a) | (b) |
|
| (c) |
Figure 2.12: Runtime behavior of a pipeline where the image processing stage runs on two threads: (a) Approximately constant acquisition interval. (b) Varying acquisition interval. (c) Varying acquisition interval leading to short-term peak loads..