1

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.

  1. Why is this the case?

  2. How can I solve this problem?

Mogsdad
  • 44,709
  • 21
  • 151
  • 275
dday
  • 47
  • 4

1 Answers1

2

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.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
  • Thank you. Now I understood the bug in code. How i make my thread that wont be pre-empted/rescheduled? – dday Dec 11 '12 at 13:11
  • You can't. Why would you want to? Imagine if there's only one core and the thread needs a lock another thread holds. If it's not pre-empted or rescheduled, you deadlock forever. I can't tell quite where, but it seems you have a misunderstanding about the whole point of threads or the division of responsibility between the scheduler and the application developer. Here's the right approach: If you don't want a thread to do something, don't code it to do that. If you'd always rather do A than B, then make your code do A and not B. – David Schwartz Dec 11 '12 at 13:11
  • Thank you. This was a doubt regarding an API in vxworks(taskLock) - which is for locking a task (in vxworks) for pre-empting – dday Dec 11 '12 at 13:25
  • 1
    Even `taskLock` doesn't do what you claim to want to do. If the thread sleeps, for example, the OS will do a context switch. Things like `taskLock` have no place on modern, general-purpose computers. If you describe your use case, I can tell you the right way to do it on a general-purpose OS. – David Schwartz Dec 11 '12 at 13:27