溫馨提示×

linux pthread怎樣設置線程優先級

小樊
133
2024-12-29 03:08:13
欄目: 智能運維

在Linux中,您可以使用pthread_setschedprio()函數來設置線程的優先級

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sched.h>

void *thread_function(void *arg) {
    printf("Thread is running.\n");
    return NULL;
}

int main() {
    pthread_t thread_id;
    struct sched_param param;
    int priority;

    // 創建一個新線程
    if (pthread_create(&thread_id, NULL, thread_function, NULL) != 0) {
        perror("Failed to create thread");
        exit(EXIT_FAILURE);
    }

    // 設置線程優先級
    priority = 10; // 您可以根據需要設置不同的優先級值(范圍為-20到19)
    param.sched_priority = priority;
    if (pthread_setschedprio(thread_id, &param) != 0) {
        perror("Failed to set thread priority");
        exit(EXIT_FAILURE);
    }

    // 等待線程完成
    pthread_join(thread_id, NULL);

    return 0;
}

在這個示例中,我們首先創建了一個名為thread_function的線程函數。然后,在main函數中,我們使用pthread_create()創建一個新線程,并使用pthread_setschedprio()設置其優先級。請注意,您需要根據您的需求設置合適的優先級值(范圍為-20到19)。最后,我們使用pthread_join()等待線程完成。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女