0

I wrote a C code programme that creates many threads (pthreads) which do all the same thing. Each of these threads tries to acquire a common mutex (one binary semaphore shared among these threads). When the first thread manages to acquire the mutex, all the other threads will find it not available (counter at 0) when they do a sem_wait (down) operation. Now, I want to do the same thing at kernel level, with a kernel module that uses Kthreads. What I've found out, is that linux kernel threads are not preemptive (preemption is not enabled on my kernel) so, as soon as the first kthread acquires the common semaphore, the others do nothing until it has finished. So, no kthread will find the mutex not available when doing a down operation on it. For my exercise, I need to have the mutex not available, every now and then, when I do the down operation, just like it happens with the version with posix threads (user level). One advice that I got is to use the schedule() function, which is called by a kthread and causes the cpu to schedule another kthread for execution. However, I am not sure how to use it. I don't understand very well what I've found on internet, since I am a newbie on kernel coding. Does anyone have an example on how to use schedule() in order to preempt kernel threads?

Discipulus
  • 245
  • 1
  • 3
  • 13
  • 1
    Kernel threads *are* preemptible. `mutex_lock()` will call `schedule()` when it's already locked. – CL. Nov 20 '13 at 08:11
  • Hum..But there is no down operation on the mutex after a thread starts running. That's the problem. It is like: many threads are created. The first one starts (random one) and executes down no the semaphore, and up at the end. ONly when the first thread finishes executing, a second thread can start (since nobady called schedule function) and will do the same, ie making down and then up on the semaphore. So, each thread will always find the semaphore available. I don't know if i am clear, and if I got what your suggestion was.. – Discipulus Nov 20 '13 at 18:58
  • Your description contradicts itself. – CL. Nov 21 '13 at 08:35
  • If your code making forward progress isn't good enough for you, then your code is broken. it's your job to do the work you want to do. – David Schwartz Nov 20 '17 at 10:36

0 Answers0