1. 虚拟化CPU
#include <stdio.h>
#include <stdlib.h>
#include "common.h"
int main(int argc, char *argv[])
{
if (argc != 2) {
fprintf(stderr, "usage: cpu <string>\n");
exit(1);
}
char *str = argv[1];
while (1) {
printf("%s\n", str);
Spin(1);
}
return 0;
}
编译:gcc -o cpu cpu.c -Wall
运行:./cpu A & ./cpu B & ./cpu C & ./cpu D &
假设上述代码在单处理器上面运行,也会输出:A,B,C,D,A,B,D,C…等等;事实证明,在硬件的帮助下,操作系统负责这种假象,即系统拥有非常多的虚拟CPU
的假象.将单个CPU
(或其中一小部分)转换为看似无限量的CPU
,这就是所谓的虚拟化CPU
2.虚拟化内存
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include "common.h"
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "usage: mem <value>\n");
exit(1);
}
int *p;
p = malloc(sizeof(int));
assert(p != NULL);
printf("(%d) addr pointed to by p: %p\n", (int) getpid(), p);
*p = atoi(argv[1]); // assign value to addr stored in p
while (1) {
Spin(1);
*p = *p + 1;
printf("(%d) value of p: %d\n", getpid(), *p);
}
return 0;
}
编译:gcc -o mem mem.c -Wall
运行:./mem 1 ./mem 2
输出:
(13294) addr pointed to by p: 0x55d1b89772a0
(13295) addr pointed to by p: 0x5571867272a0
(13294) value of p: 2
(13295) value of p: 3
(13294) value of p: 3
(13295) value of p: 4
虚拟化内存:每个进程访问自己的私有虚拟地址空间,操作系统以某种方式映射到机器的物理内存上,一个正在运行的程序中的内存引用不会影响其他进程的地址空间;
2.3并发
#include <stdio.h>
#include <stdlib.h>
#include "common.h"
#include "common_threads.h"
volatile int counter = 0;
int loops;
void *worker(void *arg) {
int i;
for (i = 0; i < loops; i++) {
counter++;
}
return NULL;
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "usage: threads <loops>\n");
exit(1);
}
loops = atoi(argv[1]);
pthread_t p1, p2;
printf("Initial value : %d\n", counter);
Pthread_create(&p1, NULL, worker, NULL);
Pthread_create(&p2, NULL, worker, NULL);
Pthread_join(p1, NULL);
Pthread_join(p2, NULL);
printf("Final value : %d\n", counter);
return 0;
}
编译:gcc -o threads threads.c -Wall -pthread
运行:./thread 1000
输出:
Initial value : 0
Final value : 2000
主程序利用Pthread_create
创建了两个线程,你可能会猜到两个线程完成时候,计数器最终值为2000;
但是当你输入:./thread 10000
时候发现输出为:
Initial value : 0
Final value : 10901
并且每次结果还不一样,这些结果与指令如何执行有关,上面程序关键是增加共享计数器的地方,需要三条指令:一条将计数器的值从内存加载到寄存器,一条将其递增,另一条将其保存回内存,因为这三条指令不是以原子方式执行,所以结果会很奇怪;
2.4持久性