我正在使用障碍来同步我的两个线程,这两个线程将分别执行task_1和task_2。
同步后,我希望优先级较高的任务在优先级较低的任务之前开始执行。
我惊讶地注意到,即使task_2的优先级低于task_1,有时task_2 在task_1之前开始执行。
#include <pthread.h>
#include <sched.h>
#include <unistd.h>
#include <errno.h>
#include <stdio.h>
#include <sys/types.h>
#define MAX_PRIORITY 99
#define MIN_PRIORITY 1
pthread_t threads[2];
pthread_barrier_t barrier;
void set_priority(int priority, int t_id){
int policy = SCHED_FIFO;
struct sched_param param;
param.sched_priority = priority;
pthread_attr_t attr;
pthread_attr_init (&attr);
pthread_setschedparam(pthread_self(), policy, ¶m);
pthread_getschedparam(pthread_self(), &policy, ¶m);
}
int set_core(int core_id) {
int num_cores = sysconf(_SC_NPROCESSORS_ONLN);
if (core_id < 0 || core_id >= num_cores)
return EINVAL;
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
CPU_SET(core_id, &cpuset);
pthread_t current_thread = pthread_self();
return pthread_setaffinity_np(current_thread, sizeof(cpu_set_t), &cpuset);
}
void create_task(int task_number, void *task) {
int rc = pthread_create(&threads[task_number - 1], NULL, task, NULL);
if(rc != 0) {
printf("pthread_create(%d) error %d\n", task_number - 1, rc);
pthread_exit(0) ;
}
}
void schedule_task(int task_number, int priority) {
set_core(2); //running tasks only in 2nd processor core
set_priority(priority, task_number);
}
void start_task_1() {
printf("Task 1 Started \n");
sleep(1); //do task 1
printf("Task 1 Endeded\n");
}
void start_task_2() {
printf("Task 2 Started \n");
sleep(1); //do task 2
printf("Task 2 Endeded\n");
}
void task_1(void *thread_param) {
schedule_task(1, MAX_PRIORITY);
pthread_barrier_wait(&barrier);
start_task_1();
pthread_exit(NULL);
}
void task_2(void *thread_param) {
schedule_task(2, MIN_PRIORITY);
pthread_barrier_wait(&barrier);
start_task_2();
pthread_exit(NULL);
}
int main() {
pthread_barrier_init(&barrier, NULL, 2);
create_task(1, task_1);
create_task(2, task_2);
for (int i = 0; i < 2; i++) {
pthread_join(threads[i], NULL);
}
pthread_barrier_destroy(&barrier);
}
这是 POSIX 线程中的预期行为吗?我能做些什么来强制task_1总是在task_2之前开始?
我以 root 身份执行程序,并确保已相应设置任务优先级。