一 register的作用(加上volatile都是让其变成易变的,防止编译器对其进行优化)
一个定义为volatile的变量是说这变量可能会被意想不到地改变,这样,编译器就不会去假设这个变量的值了。精确地说就是,优化器在用到这个变量时必须每次都小心地重新读取这个变量的值,而不是使用保存在寄存器里的备份。
就像这个图一样,如果当数据访问很快,数据在很快的变化的时候,这个时候操作系统会进行优化,他会创建一个高速指令缓存和高速数据缓存。就那这个告诉数据缓存说,会先把数据存在这个缓存器里面,后面再一起放入寄存器中。
二 使用register的场景(加上volatile都是让其变成易变的,防止编译器对其进行优化)
1)并行设备的硬件寄存器(如:状态寄存器),就比如这个在地址为0x8000 0000写入0x12345678。
#include <stdio.h>
#define ADDR (volatile unsigned int*)0x80000000
int main(int argc, char const *argv[], char* envp[])
{
*ADDR = 0x12345678;
}
2)多线程应用中被几个任务共享的变量
就比如这个,这个money就得加volatile修饰,加上volatile都是让其变成易变的,防止编译器对其进行优化。
#include <stdio.h>
#include <pthread.h>
volatile int money = 10000;
pthread_mutex_t lock;
void* task1(void* arg)
{
printf("i am thread1\n");
while (1) {
sleep(1);
pthread_mutex_lock(&lock);
money -= 50;
if (money > 0) {
printf("张三取了50块钱,剩余=%d\n", money);
} else {
printf("没钱了,张三取钱失败\n");
pthread_mutex_unlock(&lock);
pthread_exit(NULL);
}
pthread_mutex_unlock(&lock);
}
}
void* task2(void* arg)
{
printf("i am thread2\n");
while (1) {
sleep(1);
pthread_mutex_lock(&lock);
money -= 100;
if (money > 0) {
printf("李四取了100块钱,剩余=%d\n", money);
} else {
printf("没钱了,李四取钱失败\n");
pthread_mutex_unlock(&lock);
pthread_exit(NULL);
}
pthread_mutex_unlock(&lock);
}
}
int main(int argc, const char* argv[])
{
pthread_t tid1, tid2;
pthread_mutex_init(&lock,NULL);
if (pthread_create(&tid1, NULL, task1, NULL))
PRINT_ERR("create thread 1 error");
if (pthread_create(&tid2, NULL, task2, NULL))
PRINT_ERR("create thread 1 error");
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
pthread_mutex_destroy(&lock);
return 0;
}
3)一个中断服务子程序中会访问到的非自动变量
这个等我有代码例子了再回来补。