Reputation: 1210
I have just started programing on Linux kernel threads. I have a problem which I would like to share with you guys. My code is:
void do_big_things(void *data)
{
// do some really big things
}
struct task_struct *t1;
struct task_struct *t2;
void calling_fucntion()
{
for(j =0; j < 100; j++)
{
t1 = kthread_run(do_big_things, &data1, "thread1");
t2 = kthread_run(do_big_things, &data2, "thread2");
}
}
Now as far as I have concluded to this problem (I may be wrong) is that threads t1 and t2 are created and run by kernel and then program goes back at the start of loop to created and run another two threads. As there is no condition to wait for these threads to finish, the kernel creates so many threads hence causing a stack overflow.
All I want is to know that how to make program wait for these two threads to finish and then go back to loop starting another two threads.
Any help would be appreciated.
Upvotes: 5
Views: 10490
Reputation: 79
YOu can also go for completions. The linux mass storage driver http://lxr.free-electrons.com/source/drivers/usb/storage/usb.c has a very good implementation of kthreads. Good Luck.
Upvotes: 0
Reputation: 76
/* Wait for kthread_stop */
set_current_state(TASK_INTERRUPTIBLE);
while (!kthread_should_stop()) {
schedule();
set_current_state(TASK_INTERRUPTIBLE);
}
Check this article for more information: "Sleeping in the Kernel".
Upvotes: 6
Reputation: 2720
It depends what you're doing, but you may not even want to start your own kernel threads.
You can submit a job to be run on the kernel's global workqueue using schedule_work()
.
If you do use your own thread you typically write it as a loop around kthread_should_stop()
. Then the code which wants the thread to terminate calls kthread_stop()
, which tells the thread to stop and then waits for it to stop.
Upvotes: 1
Reputation: 2871
Read about wait queues. This is a good place to look at.
Essentially, you need to keep track of how many threads are running (lock protected counter), and put the creating thread on a wait queue, until all threads are done. The last thread finishing its job can wake up the thread on the wait queue, so that it can repeat the process with another pair of threads.
Upvotes: 1