6

I have a real-time thread in Linux (3.4). Under certain conditions, I want it to relinquish control to other threads with the same priority, even if it hasn't finished using up its current timeslice. I was thinking of using the following code:

if (condition) {
    resched_task();
    cond_resched();
}

however, I don't see anyone else in the code doing this, making me think there's some other (better?) way of doing this. Is there a standard way to do this?

John
  • 3,400
  • 3
  • 31
  • 47

2 Answers2

8

You can use the sched_yield() function to yield the rest of your time slice, as discussed here.

sched_yield() causes the calling thread to relinquish the CPU. The thread is moved to the end of the queue for its static priority and a new thread gets to run.

Community
  • 1
  • 1
TypeIA
  • 16,916
  • 1
  • 38
  • 52
  • Thanks. You wouldn't know the difference between sched_yield() and yield() are would you? – John Feb 13 '14 at 18:27
  • @John What yield() function are you talking about? I'm not aware of one called simply `yield()`, sorry. – TypeIA Feb 13 '14 at 19:03
  • In core.c (line 5029), there is a function called yield. On top of the function there is a big warning: `Do not ever use this function, there's a 99% chance you're doing it wrong.`... It ends up calling sys_sched_yield(), which makes me a bit weary. – John Feb 13 '14 at 19:06
  • @John Ah, that looks like something internal to the kernel. `sched_yield()` is a POSIX-standard syscall. I'm not a kernel hacker but I would certainly use the POSIX call and respect the warning you found in `core.c` :) – TypeIA Feb 13 '14 at 19:08
2

The question sounds like it's asking about kernel programming but the accepted answer is a function user mode API sched_yield(). I think the kernel answer to this question is schedule()

vharron
  • 1,138
  • 11
  • 20
  • 2
    `schedule()` doesn't put you at the back of the runqueue if the timeslice is not up, meaning that you end up waking up again right away. `yield()` does push you to the back, allowing the next process to run. After some analysis, we found that `yield()` was in fact the correct call despite the comment above it. (note - this only applies to RR runqueues though) – John Dec 13 '16 at 14:21
  • @John Are you sure schedule() doesn't put it at the end of queue? what's its purpose then. Do we relinquish cpu to get woken up right away? – Karthik Raj Palanichamy Sep 11 '17 at 12:09