아래의 코드 조각에서 6 개의 스레드를 생성 중입니다. 각각 다른 우선 순위가 있습니다. 우선 순위는 전역 우선 순위 배열에서 언급됩니다. 스레드 인덱스를 기반으로 각 스레드 내에서 전역 변수를 연속적으로 증가시키고 있습니다. 스레드 우선 순위가 높으면 개수가 더 많을 것으로 예상하고있었습니다. 그러나 내 산출물은 우선 순위 개념을 고수하고 있지 않다. 아래 표시된 출력 순서를 참조하십시오. 나는 이것을 우분투 16.04와 리눅스 커널 4.10에서 시도하고있다.리눅스 스레드 우선 순위, 동작이 비정상적입니다
O/P,
Thread=0
Thread=3
Thread=2
Thread=5
Thread=1
Thread=4
pid=32155 count=4522138740
pid=32155 count=4509082289
pid=32155 count=4535088439
pid=32155 count=4517943246
pid=32155 count=4522643905
pid=32155 count=4519640181
코드 :
#include <stdio.h>
#include <pthread.h>
#define FAILURE -1
#define MAX_THREADS 15
long int global_count[MAX_THREADS];
/* priority of each thread */
long int priority[]={1,20,40,60,80,99};
void clearGlobalCounts()
{
int i=0;
for(i=0;i<MAX_THREADS;i++)
global_count[i]=0;
}
/**
thread parameter is thread index
**/
void funcDoNothing(void *threadArgument)
{
int count=0;
int index = *((int *)threadArgument);
printf("Thread=%d\n",index);
clearGlobalCounts();
while(1)
{
count++;
if(count==100)
{
global_count[index]++;
count=0;
}
}
}
int main()
{
int i=0;
for(int i=0;i<sizeof(priority)/sizeof(long int);i++)
create_thread(funcDoNothing, i,priority[i]);
sleep(3600);
for(i=0;i<sizeof(priority)/sizeof(long int);i++)
{
printf("pid=%d count=%ld\n",getpid(),
global_count[i]);
}
}
create_thread(void *func,int thread_index,int priority)
{
pthread_attr_t attr;
struct sched_param schedParam;
void *pParm=NULL;
int id;
int * index = malloc(sizeof(int));
*index = thread_index;
void *res;
/* Initialize the thread attributes */
if (pthread_attr_init(&attr))
{
printf("Failed to initialize thread attrs\n");
return FAILURE;
}
if(pthread_attr_setschedpolicy(&attr, SCHED_FIFO))
{
printf("Failed to pthread_attr_setschedpolicy\n");
return FAILURE;
}
if (pthread_attr_setschedpolicy(&attr, SCHED_FIFO))
{
printf("Failed to setschedpolicy\n");
return FAILURE;
}
/* Set the capture thread priority */
pthread_attr_getschedparam(&attr, &schedParam);;
schedParam.sched_priority = sched_get_priority_max(SCHED_FIFO) - 1;
schedParam.sched_priority = priority;
if (pthread_attr_setschedparam(&attr, &schedParam))
{
printf("Failed to setschedparam\n");
return FAILURE;
}
pthread_create(&id, &attr, (void *)func, index);
}
입력 해 주셔서 감사합니다. 동작이 훨씬 좋은 것 같습니다. 나는 모든 경고를 고쳤다. 3600은 초기 스케쥴링 대기 시간이 카운트에 영향을 미치지 않도록 실험적이었습니다. O/P 이제, PID = 31,068 카운트 = 0 PID = 31,068 카운트 = 15 PID = 31,068 카운트 = 56,961,864 PID = 31,068 카운트 = 56,964,895 PID = 31,068 카운트 = 57,002,126 PID = 31,068 카운트 = 56,688,136 여전히 가장 높은 우선 순위 업무 행동이 그렇게 일관되지 않습니다. 나는 30 초의 수면을 시도했지만, 나는 더 높은 지체를 시도 할 것이다. 이제는 루트로서 프로그램을 실행 한 이유는 무엇입니까? –