Hi,
I am trying to learn pthreads and pthreads attributes... I wrote a simple program which creates 2 threads... 1 prints world and another prints hello... I have set priority of the thread which prints hello higher than the other so it should print hello world.. but some how it isn't doing so...
Here's the code...
Code:
#include <stdio.h>
#include <pthread.h>
#include <sched.h>
pthread_mutex_t mutex1;
char *message1 = "Hello";
char *message2 = "World";
void print_Hello( void );
void print_World( void );
int main()
{
pthread_t thread1, thread2;
pthread_attr_t atri1,atri2;
int priority_high=500, priority_low=10;
int status=0;
int t = 25;
struct sched_param para1;
struct sched_param para2;
para1.sched_priority = priority_high;
para2.sched_priority = priority_low;
status = pthread_mutex_init(&mutex1,NULL);
if(status!=0)
{
printf("\nMUTEX init failed !\n");
return 0;
}
status = pthread_attr_init(&atri1);
if(status!=0)
{
printf("\nAttribute init failed !\n");
return 0;
}
status = pthread_attr_init(&atri2);
if(status!=0)
{
printf("\nAttribute init failed !\n");
return 0;
}
status = pthread_attr_setschedpolicy(&atri1, SCHED_RR);
if(status!=0)
{
printf("\nSched policy init failed 1!\n");
return 0;
}
status = pthread_attr_setschedpolicy(&atri2, SCHED_RR);
if(status!=0)
{
printf("\nSched policy init failed 2!\n");
return 0;
}
status = pthread_attr_setschedparam(&atri1, ¶1);
if(status!=0)
{
printf("\nCould not set Priority : 1 !\n");
return 0;
}
status = pthread_attr_setschedparam(&atri2, ¶2);
if(status!=0)
{
printf("\nCould not set priority : 2!\n");
return 0;
}
while(--t>0)
{ status=pthread_create( &thread1, &atri2,(void*)&print_World, NULL);
if(status!=0)
printf("\nThread 1 Could not be created");
status= pthread_create(&thread2, &atri1,(void*)&print_Hello, NULL);
if(status!=0)
printf("\nThread 2 Could not be created");
}
return 0;
}
void print_Hello( void )
{
// while(1)
// {
pthread_mutex_lock(&mutex1);
printf("%s ", message1);
pthread_mutex_unlock(&mutex1);
// }
}
void print_World( void )
{
// while(1)
// {
pthread_mutex_lock(&mutex1);
printf("%s ", message2);
pthread_mutex_unlock(&mutex1);
// }
}
I tried changing scheduling policies, adding / removing mutex but still it keep on printing World Hello World Hello...
So, can anybody suggest what am I doing wrong?
Thanks,
Edesign