I have executed the below program several times, most of the time i got the same out put but some times output is different.
sample out put is:
skylab@skylab:~/Nx/Thrds$ gcc 3.c -lpthread
skylab@skylab:~/Nx/Thrds$ ./a.out
Scheduling policy = ???
arg = 20
1arg = 20
thrd 1 schded
2arg = 10
thrd 2 schded
skylab@skylab:~/Nx/Thrds$ ./a.out
Scheduling policy = ???
arg = 20
1arg = 20
thrd 1 schded
2arg = 10
thrd 2 schded
skylab@skylab:~/Nx/Thrds$ ./a.out
Scheduling policy = ???
arg = 20
1arg = 20
thrd 1 schded
2arg = 10
thrd 2 schded
skylab@skylab:~/Nx/Thrds$ ./a.out
Scheduling policy = ???
arg = 20
1arg = 20
2arg = 20
thrd 1 schded
thrd 2 schded
skylab@skylab:~/Nx/Thrds$ ./a.out
Scheduling policy = ???
arg = 20
1arg = 20
2arg = 20
thrd 2 schded
thrd 1 schded
As far as my understanding the threads are not getting scheduled in FIFO order.
my expected output is:
arg = 20
thrd 1 schded
1arg = 10
thrd 2 schded
2arg = 30
Scheduling policy = ??? - i printed this just to know what policy kernel is using.
is there any way i can get my expected out as actual, without modifying scheduling policy?
Please Help.
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#define handle_error_en(en, msg) \
do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0)
void *fun1(void* );
void *fun2(void* );
int arg = 20;
int main( void ) {
pthread_t tid1,tid2;
pthread_attr_t attr;
int i;
int s = pthread_attr_getschedpolicy(&attr, &i);
if (s != 0)
handle_error_en(s, "pthread_attr_getschedpolicy");
printf("Scheduling policy = %s\n",
(i == SCHED_OTHER) ? "SCHED_OTHER" :
(i == SCHED_FIFO) ? "SCHED_FIFO" :
(i == SCHED_RR) ? "SCHED_RR" :
"???");
attr
printf(" arg = %d\n", arg);
pthread_create(&tid1, NULL, fun1,NULL);
printf(" 1arg = %d\n", arg);
pthread_create(&tid2, NULL, fun2,NULL);
printf(" 2arg = %d\n", arg);
pthread_exit(&tid1);
pthread_exit(&tid2);
return 0;
}
pthread_mutex_t mutex= PTHREAD_MUTEX_INITIALIZER;
void * fun1( void *p)
{
printf(" thrd 1 schded \n");
pthread_mutex_lock(&mutex);
if (arg == 20)
arg = 10;
pthread_mutex_unlock(&mutex);
}
void* fun2( void *p)
{
printf(" thrd 2 schded \n");
pthread_mutex_lock(&mutex);
if (arg == 10)
arg = 30;
pthread_mutex_unlock(&mutex);
}
Output :