close

#include <fcntl.h>
#include <sys/stat.h>
#include <errno.h>
#include <sys/mman.h>
#include <sys/types.h> //shm_open
#include <stdio.h>  //printf
#include <stdlib.h> //exit
#include <unistd.h> //close
#include <string.h> //strerror

/* This will be created under /dev/shm/ */
#define STATE_FILE "/program.shared"
#define  NAMESIZE 1024
#define   MAXNAMES 100

struct st1
{
  char name[12];
  int heartbeat ;
  double price ;
  int iFlag ;
} ;

struct st2  {
    struct st1 ;
    char pad[64 - sizeof(struct st1)] ;
} __attribute__((aligned(64))) ;

int main (void)
{
int first = 0;
int shm_fd;
static struct st2 *conf;

  //if((shm_fd = shm_open(STATE_FILE, (O_CREAT | O_RDWR),
  if((shm_fd = shm_open(STATE_FILE, (O_RDWR),
                        (S_IREAD | S_IWRITE))) < 0) {
   /* Try to open the shm instance normally and share it with
    * existing clients
    */
    printf("Could not create shm object. %s\n", strerror(errno));
    return errno;
  }

  /* Set the size of the SHM to be the size of the struct. */
  //ftruncate(shm_fd, sizeof(SHARED_VAR));
  ftruncate(shm_fd, sizeof(struct st2)*10 );

  if((conf =  mmap(0, sizeof(struct st2)*10 , (PROT_READ | PROT_WRITE),
                   MAP_SHARED, shm_fd, 0)) == MAP_FAILED) {

    return errno;

  }

  if(first) {
   /* Run a set up for the first time, fill some args */
   printf("First creation of the shm. Setting up default values\n");
  }
  else
  {
      int idx,idy ;
      for(idx=0;idx< 100000000;idx++)
      {
          for(idy=0;idy<10;idy++)
          {
              while (__sync_lock_test_and_set(&((conf+idy)->iFlag), 1))
                  while ((conf+idy)->iFlag)
                      __asm volatile ("pause" ::: "memory");

              (conf+idy)->heartbeat = (conf+idy)->heartbeat + 1 ;

              __sync_lock_release(&((conf+idy)->iFlag));
          }//for idy
      }//for
      int idz ;
      for(idz=0;idz<10;idz++)
          printf("(conf+idz)->heartbeat=(%d)\n",(conf+idz)->heartbeat) ;
  }

  exit(0);
}

 

 

 

arrow
arrow
    全站熱搜

    hedgezzz 發表在 痞客邦 留言(0) 人氣()