hi guys, this is my code
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sched.h>
#include <stdlib.h>
#define THREAD_ID pthread_self()
#define PRIORITY1 4
#define PRIORITY2 3
int count = 0;
int policy;
pthread_t thread1, thread2;
pthread_attr_t attr1, attr2, attr;
struct sched_param param1, param2;
struct sched_param param;
pthread_mutex_t mutex;
void*
fnThread()
{
while(count < 10) {
pthread_mutex_lock(&mutex);
pthread_getschedparam(THREAD_ID, &policy, ¶m);
printf("thread: %lu, priority: %d, policy: %d, count: %d\n",
(unsigned long)THREAD_ID, param.sched_priority, policy, count++);
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
int
main ( int argc, char *argv[] )
{
pthread_mutex_init(&mutex, NULL);
pthread_attr_init(&attr);
pthread_attr_init(&attr2);
pthread_attr_setschedpolicy(&attr1, SCHED_FIFO);
pthread_attr_setschedpolicy(&attr2, SCHED_FIFO);
param1.sched_priority = PRIORITY1;
pthread_attr_setschedparam(&attr1, ¶m1);
param2.sched_priority = PRIORITY2;
pthread_attr_setschedparam(&attr2, ¶m2);
pthread_create(&thread1, &attr1, &fnThread, NULL);
pthread_create(&thread2, &attr2, &fnThread, NULL);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
pthread_attr_destroy(&attr1);
pthread_attr_destroy(&attr2);
pthread_mutex_destroy(&mutex);
return EXIT_SUCCESS;
}
main function contains 2 threads, all of threads execute only function
fnThread. Task of function is printing
thread id,
priority and
policy of thread onto screen (10 times).
and result:
thread: 3078544240, priority: 0, policy: 0, count: 0
thread: 3070151536, priority: 0, policy: 0, count: 1
thread: 3078544240, priority: 0, policy: 0, count: 2
thread: 3070151536, priority: 0, policy: 0, count: 3
thread: 3078544240, priority: 0, policy: 0, count: 4
thread: 3070151536, priority: 0, policy: 0, count: 5
thread: 3078544240, priority: 0, policy: 0, count: 6
thread: 3070151536, priority: 0, policy: 0, count: 7
thread: 3070151536, priority: 0, policy: 0, count: 8
thread: 3078544240, priority: 0, policy: 0, count: 9
this is unexpected result. Instead displays
priority as
3 in
thread1 (or
4 in
thread2), and display
policy as
1 (SCHED_FIFO is defined as 1),but all equal 0. Why don't get exactly priority and policy of thread? Please help me, thanks so much!