当前位置:   article > 正文

pthread创建周期10ms线程_pthread_create耗时

pthread_create耗时

#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;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

}

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, &params);
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;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52

}

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/182005
推荐阅读
相关标签
  

闽ICP备14008679号