赞
踩
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <time.h>
#define PERIOD_NS 10000000 // 10ms
void* threadFunction(void* arg)
{
struct timespec start, end, sleepTime;
sleepTime.tv_sec = 0;
sleepTime.tv_nsec = PERIOD_NS;
while (1) { // 获取当前时间 clock_gettime(CLOCK_MONOTONIC, &start); // 打印时间 printf("Current time: %ld seconds, %ld nanoseconds\n", start.tv_sec, start.tv_nsec); // 计算实际睡眠时间 clock_gettime(CLOCK_MONOTONIC, &end); long sleepDuration = PERIOD_NS - (end.tv_nsec - start.tv_nsec); if (sleepDuration < 0) { sleepTime.tv_nsec = 0; } else { sleepTime.tv_nsec = sleepDuration; } // 线程睡眠 nanosleep(&sleepTime, NULL); } return NULL;
}
int main()
{
pthread_t thread;
pthread_attr_t attr;
int result;
// 初始化线程属性 result = pthread_attr_init(&attr); if (result != 0) { printf("Failed to initialize thread attributes.\n"); return EXIT_FAILURE; } // 设置线程优先级为次高 result = pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED); if (result != 0) { printf("Failed to set thread inheritance attribute.\n"); return EXIT_FAILURE; } result = pthread_attr_setschedpolicy(&attr, SCHED_FIFO); if (result != 0) { printf("Failed to set thread scheduling policy.\n"); return EXIT_FAILURE; } struct sched_param params; int maxPriority = sched_get_priority_max(SCHED_FIFO); params.sched_priority = maxPriority - 1; // 设置为次高优先级 result = pthread_attr_setschedparam(&attr, ¶ms); if (result != 0) { printf("Failed to set thread scheduling parameters.\n"); return EXIT_FAILURE; } // 创建线程 result = pthread_create(&thread, &attr, threadFunction, NULL); if (result != 0) { printf("Failed to create thread.\n"); return EXIT_FAILURE; } // 销毁线程属性 result = pthread_attr_destroy(&attr); if (result != 0) { printf("Failed to destroy thread attributes.\n"); return EXIT_FAILURE; } // 打印最高优先级值 printf("Maximum priority: %d\n", maxPriority); // 主线程等待线程结束 result = pthread_join(thread, NULL); if (result != 0) { printf("Failed to join thread.\n"); return EXIT_FAILURE; } return EXIT_SUCCESS;
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。