Вопрос PERMEMPT_RT: лучшие практики однопоточной однопоточной программы (пользовательское пространство)Linux

Ответить Пред. темаСлед. тема
Anonymous
 Вопрос PERMEMPT_RT: лучшие практики однопоточной однопоточной программы (пользовательское пространство)

Сообщение Anonymous »

Прилагается код, как мне сделать его более понятным или улучшить документацию? Думаю, я понимаю, как мне нужно заблокировать память и.....
  • Блокировка памяти:

    Использует mlockall для блокировки текущего и будущего распределения памяти, предотвращая подкачку.
[*]Атрибут потока
< ul>
Инициализация: инициализирует атрибуты pthread и устанавливает минимальный размер стека для потока.


[*]Политика и приоритет планирования:
  • Задает политику планирования SCHED_FIFO и проверяет, находится ли приоритет в пределах, поддерживаемых системой.
[*]Создание и очистка потока:
  • Создает поток и ожидает завершения его выполнения. После этого он уничтожает атрибуты pthread, чтобы освободить ресурсы.

/*
* POSIX Real-Time Thread Example with CPU Affinity
* This code creates a single real-time pthread that performs a dummy math operation in a loop
* and calculates the time taken for each loop cycle.
*
* Compilation:
* {WHATEVER}-gcc -o rt_example rt_example.c -lrt -lpthread -lm
*/

#define _GNU_SOURCE

#include // For pthreads and related functions
#include // For setting scheduling policies and CPU affinity
#include // For memory locking
#include // For math operations
#include // For standard I/O
#include // For standard library functions
#include // For system limits
#include // For time measurement functions

// GOALS
// This function is the main task that runs in real-time.
// It sets the CPU affinity to core 0, performs a dummy math operation in a loop,
// and measures the elapsed time for each cycle.
// It prints the elapsed time every 100 cycles.
void *thread_func(void *arg) {
cpu_set_t cpuset;
CPU_ZERO(&cpuset); // Initialize CPU set to empty
CPU_SET(0, &cpuset); // Set CPU affinity to core 0

// Attempt to set CPU affinity to CPU 0 for this thread
if (sched_setaffinity(0, sizeof(cpuset), &cpuset)) {
perror("sched_setaffinity failed");
return NULL;
}

// Time struct to specify sleep duration
struct timespec time_requested = {0, 10000000}; // 10 milliseconds

// Time structs to record start and end times for each loop iteration
struct timespec start, end;
float x = 1.5f; // Dummy variable for math operation

// Infinite loop to simulate a real-time task
int count = 0;
while (1) {
// Record the start time of this cycle
clock_gettime(CLOCK_MONOTONIC, &start);

// Perform a dummy math operation to simulate workload
x *= sin(x) / atan(x) * tanh(x) * sqrt(x);

// Sleep for 10 milliseconds to give lower priority threads CPU time
nanosleep(&time_requested, NULL);

// Record the end time of this cycle
clock_gettime(CLOCK_MONOTONIC, &end);

// Calculate elapsed time in nanoseconds
long elapsed_ns = (end.tv_sec - start.tv_sec) * 1000000000L + (end.tv_nsec - start.tv_nsec);

// Print elapsed time every 100 cycles to reduce console spam
if (count++ % 100 == 0) {
printf("Loop cycle time: %ld ns\n", elapsed_ns);
}
}

return NULL;
}

// GOALS
// Memory Locking:
// Uses mlockall to lock current and future memory allocations, preventing paging.
// Thread Attribute
// Initialization: Initializes pthread attributes and sets a minimal stack size for the thread.
// Scheduling Policy and Priority:
// Sets the scheduling policy to SCHED_FIFO and checks that the priority falls within system-supported limits.
// Thread Creation and Cleanup:
// Creates the thread and waits for it to finish execution. Afterward, it destroys the pthread attributes to release resources.
int main(int argc, char* argv[]) {
struct sched_param param; // Scheduling parameters structure
pthread_attr_t attr; // Thread attributes structure
pthread_t thread; // Thread identifier
int ret; // Return value for error checking

// Lock memory to prevent paging, enhancing real-time performance
if (mlockall(MCL_CURRENT|MCL_FUTURE) == -1) {
perror("mlockall failed");
exit(-2);
}

// Initialize thread attributes with default values
if ((ret = pthread_attr_init(&attr))) {
perror("pthread_attr_init failed");
goto out;
}

// Set minimum stack size for the thread, can be increased if needed
if ((ret = pthread_attr_setstacksize(&attr, PTHREAD_STACK_MIN))) {
perror("pthread_attr_setstacksize failed");
goto out;
}

// Set scheduling policy to FIFO (First In, First Out) for real-time priority
if ((ret = pthread_attr_setschedpolicy(&attr, SCHED_FIFO))) {
perror("pthread_attr_setschedpolicy failed");
goto out;
}

// Set the thread's scheduling priority to 79 (within the real-time range)
param.sched_priority = 79;
int max_priority = sched_get_priority_max(SCHED_FIFO);
int min_priority = sched_get_priority_min(SCHED_FIFO);

// Verify that the priority level is within system-supported limits
if (param.sched_priority > max_priority || param.sched_priority < min_priority) {
printf("Priority %d out of range (%d-%d)\n", param.sched_priority, min_priority, max_priority);
exit(-1);
}

// Apply the scheduling parameters to the thread attributes
if ((ret = pthread_attr_setschedparam(&attr, &param))) {
perror("pthread_attr_setschedparam failed");
goto out;
}

// Explicitly use the scheduling parameters set in the attributes
if ((ret = pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED))) {
perror("pthread_attr_setinheritsched failed");
goto out;
}

// Create the real-time thread using the specified attributes and function
if ((ret = pthread_create(&thread, &attr, thread_func, NULL))) {
perror("pthread_create failed, are you root?");
goto out;
}

// Wait for the thread to finish execution (in this case, indefinitely)
if ((ret = pthread_join(thread, NULL))) {
perror("pthread_join failed");
}

out:
// Clean up the thread attributes after thread creation
if (pthread_attr_destroy(&attr)) {
perror("pthread_attr_destroy failed");
return -1;
}

return ret;
}



Подробнее здесь: https://stackoverflow.com/questions/791 ... -practices
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Linux»