gpt4 book ai didi

克隆系统调用和互斥

转载 作者:行者123 更新时间:2023-11-30 16:02:19 25 4
gpt4 key购买 nike

我正在尝试使用克隆系统调用和一个由 2 个线程共享的递增计数器的小示例进行练习。代码如下:

#define _GNU_SOURCE
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <stdio.h>
#include <sched.h>

#include "error.h"

/*------------------------- Mutual exclusion ------------------------------*/

void EnterCZ()

{
if (sched_setscheduler(getpid(), SCHED_FIFO, &(struct sched_param) { .sched_priority = 1 }) == -1)
SysError("EntrarZC:sched_setscheduler");
}

void ExitCZ()
{
if (sched_setscheduler(getpid(), SCHED_OTHER, &(struct sched_param) { .sched_priority = 0 }) == -1)
SysError("SalirZC:sched_setscheduler");
}

/*-------------------------------------------------------------------------*/

#define STACK_SIZE 65536
#define N 100000

int main(int argc, char *argv[])
{
int n = 0;
char *stack;

int Child(void *args) {
int i, temp;

for (i = 0; i < N; i++) {
EnterCZ();
temp = n;
temp++;
n = temp;
ExitCZ();
}
return 0;
}

printf("initial n = %d\n", n);

if ((stack = malloc(STACK_SIZE)) == NULL)
RTError("main:malloc");
if (clone(Child, stack + STACK_SIZE, SIGCHLD | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_VM, NULL) == -1)
SysError("main:clone");
if ((stack = malloc(STACK_SIZE)) == NULL)
RTError("main:malloc");
if (clone(Child, stack + STACK_SIZE, SIGCHLD | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_VM, NULL) == -1)
SysError("main:clone");

while (wait(NULL) != -1) ;

printf("final n = %d\n", n);

return 0;
}

执行结果为:

initial n = 0
final n = 199999

应该是200000,所以通过提高优先级的方式互斥失败了,为什么?

最佳答案

这里有几个问题:

  • 多个 SCHED_FIFO 进程可以在多个 CPU 上同时运行。
  • 如果 SCHED_FIFO 进程超过 RLIMIT_RTTIME 软/硬限制,则可能/将会被终止。
  • 没有什么可以阻止编译器对指令重新排序。
  • 没有什么可以阻止 CPU 对指令重新排序。

关于克隆系统调用和互斥,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5422281/

25 4 0