在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, ¶m) != 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()
等待線程完成。