进程中预定义的抢占点

时间:2013-07-28 17:19:08

标签: process fork semaphore

我已经分叉了许多子进程,并为每个进程分配了优先级和核心。 Porcess A以3秒的周期执行,处理B以6秒的周期执行。我希望它们以这样的方式执行:优先级较高的进程应该只在预定义的点上抢占较低优先级的进程,并试图用信号量来实现它。我在2个进程中使用了相同的代码片段,两者中的数组值都不同。

'bubblesort_desc()'按降序对数组进行排序并打印出来。 'bubblesort_asc()'按升序排序并打印。

while(a<3)  
{
printf("time in sort1.c: %d %ld\n", (int)request.tv_sec, (long int)request.tv_nsec);
int array[SIZE] = {5, 1, 6 ,7 ,9};

semaphore_wait(global_sem);
     bubblesort_desc(array, SIZE);
semaphore_post(global_sem);

semaphore_wait(global_sem);
    bubblesort_asc(array, SIZE); 
semaphore_post(global_sem);

semaphore_wait(global_sem);     
a++;

request.tv_sec = request.tv_sec + 6;
request.tv_nsec = request.tv_nsec; //if i add 1ms here like an offset to the lower priority one, it works.  

semaphore_post(global_sem);
semaphore_close(global_sem);    //close the semaphore file

//sleep for the rest of the time after the process finishes execution until the period of 6
clk = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &request, NULL);
if (clk != 0 && clk != EINTR)
    printf("ERROR: clock_nanosleep\n");

}

每当两个进程同时被激活时,我得到这样的输出。例如,时间单位为6,12,..

time in sort1.c: 10207 316296689
time now in sort.c: 10207 316296689
9
99
7
100
131
200
256
6
256
200
5
131
100
99
1
1
5
6
7
9

当一组排序列表正在打印时,一个进程不应该抢占另一个进程。但它的工作就好像没有信号量一样。我根据以下链接定义了信号量:http://linux.die.net/man/3/pthread_mutexattr_init

谁能告诉我这是什么原因?有没有比信号量更好的替代方案?

1 个答案:

答案 0 :(得分:0)

它的printf导致模糊输出。如果结果打印时没有'\ n',那么我们会得到更准确的结果。但它总是更好地避免实时应用程序的printf语句。我使用trace-cmd和kernelshark来可视化进程的行为。

相关问题