Reputation: 47
I have a process which contain two threads. I want to schedule them based on their priority(SCHED_RR policy)
. Let t1, t2 denote these threads, both having priority 1 (lowest) initially.
I want to make sure that my thread t1 is not preempted/rescheduled while it is doing critical task - so I boost its priority to maximum before the critical task and reduce it to the original value after the critical task:
thread_proc_t1() {
while(1) {
if(critical condition happens) {
set_priority_max();
}
printf("t1");
usleep(xxx);
if(critical task finished ) {
reset_priority();
}
}
}
thread_proc_t2() {
while(1) {
printf("t2");
usleep(xxx);
}
}
I expect the printf()
commands in thread t2 not to be executed after I've called set_priority_max()
in thread t1. But the output does contains prints from thread t2 also.
Why is this the case?
How can I solve this problem?
Upvotes: 1
Views: 830
Reputation: 182763
There's no problem, this is expected behavior.
First, if you have more than one core, then the priorities won't matter if there are fewer ready-to-run threads than cores -- each thread will get its own core.
Second, your high-priority thread sleeps, which gives the lower-priority thread time to run.
Third, your threads interact through the lock that protects standard output. The higher-priority thread can be waiting for that lock, allowing lower-priority threads to run.
Please don't try to use priorities this way. It adds massive complexity, hurts performance, and rarely accomplishes anything useful.
Upvotes: 2