Chinaunix首页 | 论坛 | 博客
  • 博客访问: 35991
  • 博文数量: 23
  • 博客积分: 1415
  • 博客等级: 上尉
  • 技术积分: 235
  • 用 户 组: 普通用户
  • 注册时间: 2009-02-20 09:41
文章分类
文章存档

2011年(1)

2010年(2)

2009年(20)

我的朋友

分类: C/C++

2010-01-03 22:18:21

volatile说明变量是容易变化的,与编译过程中的优化有关。比如在循环中的指示变量并不在循环体中重新赋值,编译器可能会把这个指示变量拷贝到寄存器中以加快速度。但是实际上这个指示变量在循环过程中可能被其它进程所改变。 以下举sinal机制中的一个例子以说明。


#include <signal.h>
#include <stdio.h>
#include <stdlib.h>

/* This flag controls termination of the main loop. */
volatile sig_atomic_t keep_going = 1;

/* The signal handler just clears the flag and re-enables itself. */
void
catch_alarm (int sig)
{
  keep_going = 0;
  signal (sig, catch_alarm);
}

void
do_stuff (void)
{
  puts ("Doing stuff while waiting for alarm....");
}

int
main (void)
{
  /* Establish a handler for SIGALRM signals. */
  signal (SIGALRM, catch_alarm);

  /* Set an alarm to go off in a little while. */
  alarm (2);

  /* Check the flag once in a while to see when to quit. */
  while (keep_going)
    do_stu#include <signal.h>
#include <stdio.h>
#include <stdlib.h>

/* This flag controls termination of the main loop. */
volatile sig_atomic_t keep_going = 1;

/* The signal handler just clears the flag and re-enables itself. */
void
catch_alarm (int sig)
{
  keep_going = 0;
  signal (sig, catch_alarm);
}

void
do_stuff (void)
{
  puts ("Doing stuff while waiting for alarm....");
}

int
main (void)
{
  /* Establish a handler for SIGALRM signals. */
  signal (SIGALRM, catch_alarm);

  /* Set an alarm to go off in a little while. */
  alarm (2);

  /* Check the flag once in a while to see when to quit. */
  while (keep_going)
    do_stuff ();

  return EXIT_SUCCESS;
}
ff ();

  return EXIT_SUCCESS;
}


阅读(403) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~