Implementing priority based preemtive pthread
Hi..
I am trying to create 2 pthreads from my main thread with different scheduling priorities. I want to create a scenario when one of my threads (running at higher priority) is not preempted by the other thread (which is at lower priority) until it finishes its job.
For this purpose, I have set different priorities (5, 10) to my threads and have set the scheduling algorithm to SCHED_FIFO for both of them.
I am using pthread_setschedparam().
Within both of my threads, I have put infinite loops.
I would expect the thread running at higher priority to continue indefinitely. However in this case both the threads are getting executed in a round robin fashion.
My kernel version is - 2.6.18-1.2798.fc6xen
Can anyone please help me ? Will appreciate a response.
Below is the code snippet for reference.
#include <stdio.h>
#include <unistd.h>
#include <linux/unistd.h>
#include <sys/types.h>
#include <sys/syscall.h>
#include <sched.h>
#include <pthread.h>
#include <string.h>
#include <errno.h>
pthread_t thread1, thread2;
void (*FuncPointer)(int);
void Func1(void * pI)
{
int i = 0, err = 0;
struct sched_param new_sched_param;
memset(&new_sched_param, 0, sizeof(struct sched_param));
new_sched_param.sched_priority = 10;
err = pthread_setschedparam(thread1, SCHED_FIFO, &new_sched_param);
if(0 != err) {
printf("Inside Func1..pthread_setschedparam failed with %d", err);
return;
}
for(; ; ) {
printf("Inside Func1 - Running with priority %d.\n", new_sched_param.sched_priority);
}
return;
}
void Func2(void * pI)
{
int i = 0, err = 0;
struct sched_param new_sched_param;
memset(&new_sched_param, 0, sizeof(struct sched_param));
new_sched_param.sched_priority = 10;
err = pthread_setschedparam(thread2, SCHED_FIFO, &new_sched_param);
if(0 != err) {
printf("Inside Func2..pthread_setschedparam failed with %d", err);
return;
}
for(; ; ) {
printf("Inside Func2 - Running with priority %d.\n", new_sched_param.sched_priority);
}
return;
}
int main()
{
int err = 0;
printf("Entered main....Starting threads..\n");
pthread_create(&thread1, NULL, Func1, NULL);
pthread_create(&thread2, NULL, Func2, NULL);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
return 0;
}
|