Пример #1
0
void btif_debug_conn_state(const bt_bdaddr_t bda, const btif_debug_conn_state_t state,
    const tGATT_DISCONN_REASON disconnect_reason) {
  next_event();

  conn_event_t *evt = &connection_events[current_event];
  evt->ts = btif_debug_ts();
  evt->state = state;
  evt->disconnect_reason = disconnect_reason;
  memcpy(&evt->bda, &bda, sizeof(bt_bdaddr_t));
}
Пример #2
0
Файл: input06.c Проект: kraj/ltp
static int parse_autorepeat_config(struct input_event *iev)
{
	if (!check_event_code(iev, EV_REP, REP_DELAY)) {
		tst_resm(TFAIL,
			 "Didn't get EV_REP configuration with code REP_DELAY");
		return 0;
	}

	if (!check_event_code(next_event(), EV_REP, REP_PERIOD)) {
		tst_resm(TFAIL,
			 "Didn't get EV_REP configuration with code REP_PERIOD");
		return 0;
	}

	return 1;
}
Пример #3
0
void
_eglutNativeEventLoop(void)
{
   while (1) {
      struct eglut_window *win = _eglut->current;

      next_event(win);

      if (_eglut->redisplay) {
         _eglut->redisplay = 0;

         if (win->display_cb)
            win->display_cb();
         eglSwapBuffers(_eglut->dpy, win->surface);
      }
   }
}
Пример #4
0
int stack::simulation()
{
// set printout conditions
   set_runparms();

// any changes to simulation run profile set in pwan1.cpp should be inserted here
//
// some good examples are:
//
//   internet = TRUE;                        // use internet notation for hosts
//   interactive = TRUE;                     // makes output interactive 
//   max_DES_ticks = 500000;                 // changes simulation limit 
//   diskout = NULL;                         // turns off disk output   
//   print_at[frame_send_interface] = FALSE; // turns off/on layer trace  
//   number_of_hosts_sending_email = 1;      // simplifies traffic for debug
//   link_bit_error_rate = 0;                // stops bit errors for debug 
//

// print out authors
   print_authors();
// initialize network
   if(read_net())
   {
     if(wan)create_topology();
     print_topology();
     if(wan)startup_routing();
     if(multicast)
     {
       create_mc_topology();
       print_mc_topology();
     }
     startup_simulation();
   }
// run simulation
   while(next_event());
   statistics();
   return SUCCESS;
}
agency::cuda::async_future<agency::detail::result_of_t<ResultFactory()>>
  launch_bulk_then_execute_concurrent_kernel_impl(agency::cuda::device_id device,
                                                  agency::cuda::detail::stream&& stream, Function f,
                                                  ::dim3 grid_dim,
                                                  Shape block_dim,
                                                  const agency::cuda::detail::asynchronous_state<T>& predecessor_state,
                                                  ResultFactory result_factory,
                                                  OuterFactory outer_factory,
                                                  InnerFactory inner_factory)
{
  // create the asynchronous state to store the result
  using result_type = agency::detail::result_of_t<ResultFactory()>;
  detail::asynchronous_state<result_type> result_state = detail::make_asynchronous_state(result_factory);
  
  // create the asynchronous state to store the outer shared argument
  using outer_arg_type = agency::detail::result_of_t<OuterFactory()>;
  detail::asynchronous_state<outer_arg_type> outer_arg_state = detail::make_asynchronous_state(outer_factory);

  // wrap up f and its arguments into a closure to execute in a kernel
  const size_t block_dimension = agency::detail::shape_size<Shape>::value;
  auto closure = detail::make_bulk_then_execute_closure<block_dimension>(f, predecessor_state.data(), result_state.data(), outer_arg_state.data(), inner_factory);

  // make the kernel to launch
  auto kernel = detail::make_cuda_kernel(closure);

  // launch the kernel
  detail::try_launch_cooperative_kernel_on_device(kernel, grid_dim, detail::make_dim3(block_dim), 0, stream.native_handle(), device.native_handle(), closure);

  // create the next event
  detail::event next_event(std::move(stream));

  // schedule the outer arg's state for destruction when the next event is complete
  detail::invalidate_and_destroy_when(outer_arg_state, next_event);

  // return a new async_future corresponding to the next event & result state
  return detail::make_async_future(std::move(next_event), std::move(result_state));
}
Пример #6
0
int main(int argc, char *argv[])
{
	char *iface = "wlan0";
	char *tap = "tap0";
	struct params p;
	int ch;

	/* default params */
	memset(&p, 0, sizeof(p));
	memcpy(p.mac, "\x00\x00\xde\xfa\xce\x0d", 6);
	strcpy(p.ssid, "sorbo");
	p.bint = 500*1000;
	p.seq = getpid();
	if (gettimeofday(&p.blast, NULL) == -1)
		err(1, "gettimeofday()");
	p.chan = 3;

	while ((ch = getopt(argc, argv, "hi:s:m:w:c:t:")) != -1) {
		switch (ch) {
		case 'i':
			iface = optarg;
			break;
		case 't':
			tap = optarg;
			break;

		case 'c':
			p.chan = atoi(optarg);
			break;

		case 's':
			strncpy(p.ssid, optarg, sizeof(p.ssid)-1);
			p.ssid[sizeof(p.ssid)-1] = 0; 
			break;

		case 'm':
			str2mac(p.mac, optarg);
			break;

		case 'w':
			if (str2wep(p.wep_key, &p.wep_len, optarg)) {
				printf("Error parsing WEP key\n");
				exit(1);
			}
			break;

		case 'h':
		default:
			usage(argv[0]);
			break;
		}
	}

	/* init */
	if ((p.tx = open_tx(iface)) == -1)
		err(1, "open_tx()");
	if ((p.rx = open_rx(iface)) == -1)
		err(1, "open_rx()");

	if ((p.tap = open_tap(tap)) == -1)
		err(1, "open_tap()");
	if (set_iface_mac(tap, p.mac) == -1)
		err(1, "set_iface_mac()");

	while (1) {
		next_event(&p);
	}

	exit(0);
}
Пример #7
0
/**
 * @brief
 * 		simulate the future of a PBS universe
 *
 * @param[in] 	policy   - policy info
 * @param[in] 	sinfo    - PBS universe to simulate
 * @param[in] 	cmd      - simulation command
 * @param[in] 	arg      - optional argument
 * @param[out] 	sim_time - the time in the simulated universe
 *
 * @return	bitfield of what type of event(s) were simulated
 */
unsigned int
simulate_events(status *policy, server_info *sinfo,
	enum schd_simulate_cmd cmd, void *arg, time_t *sim_time)
{
	time_t event_time = 0;	/* time of the event being simulated */
	time_t cur_sim_time = 0;	/* current time in simulation */
	unsigned int ret = 0;
	event_list *calendar;

	timed_event *event;		/* the timed event to take action on */

	if (sinfo == NULL || sim_time == NULL)
		return TIMED_ERROR;

	if (cmd == SIM_TIME && arg == NULL)
		return TIMED_ERROR;

	if (cmd == SIM_NONE)
		return TIMED_NOEVENT;

	if (sinfo->calendar == NULL)
		return TIMED_NOEVENT;

	if (sinfo->calendar->current_time ==NULL)
		return TIMED_ERROR;

	calendar = sinfo->calendar;

	event = next_event(sinfo, DONT_ADVANCE);

	if (event == NULL)
		return TIMED_NOEVENT;

	if (event->disabled)
		event = next_event(sinfo, ADVANCE);

	if (event == NULL)
		return TIMED_NOEVENT;

	cur_sim_time = (*calendar->current_time);

	if (cmd == SIM_NEXT_EVENT) {
		long t = 0;
		if(arg != NULL)
			t = *((long *) arg);
		event_time = event->event_time + t;
	}
	else if (cmd == SIM_TIME)
		event_time = *((time_t *) arg);

	while (event != NULL && event->event_time <= event_time) {
		cur_sim_time = event->event_time;

		(*calendar->current_time) = cur_sim_time;
		if (perform_event(policy, event) == 0) {
			ret = TIMED_ERROR;
			break;
		}

		ret |= event->event_type;

		event = next_event(sinfo, ADVANCE);
	}

	(*sim_time) = cur_sim_time;

	if (cmd == SIM_TIME) {
		(*sim_time) = event_time;
		(*calendar->current_time) = event_time;
	}

	return ret;
}
Пример #8
0
Файл: test.c Проект: RTS2/rts2
int
main (int argc, char **argv)
{
  time_t start_time;
  time_t end_time;
  time_t ev_time;
  time_t last_event = 0;
  struct ln_lnlat_posn *obs;
  int type, curr_type;
  int ndays = 5;
  int c;

  Rts2Config *config = Rts2Config::instance ();
  config->loadFile ();

  obs = config->getObserver ();
  ev_time = time (NULL);

  while (1)
    {
      c = getopt (argc, argv, "a:n:l:ht:");
      if (c == -1)
	break;
      switch (c)
	{
	case 'a':
	  obs->lat = atof (optarg);
	  break;
	case 'l':
	  obs->lng = atof (optarg);
	  break;
	case 'n':
	  ndays = atoi (optarg);
	  if (!ndays)
	    {
	      fprintf (stderr, "Invalid number of days: %i\n", ndays);
	      exit (1);

	    }
	  break;
	case 't':
	  ev_time = atoi (optarg);
	  if (!ev_time)
	    {
	      fprintf (stderr, "Invalid time: %s\n", optarg);
	      exit (1);
	    }
	  break;
	case '?':
	case 'h':
	  usage ();
	default:
	  fprintf (stderr, "Getopt returned unknow character %o\n", c);
	}
    }

  rise_set_cal (obs, &ev_time, ndays);

  start_time = ev_time;

  end_time = start_time + 86500 * ndays;
  for (; start_time < end_time; start_time += 60)
    {
      if (next_event (obs, &start_time, &curr_type, &type, &ev_time))
	{
	  printf ("error!!\n");
	  return EXIT_FAILURE;
	}

      if (last_event != ev_time)
	{

	  printf ("\nt: %li time: %s\n\n\n", ev_time, ctime (&start_time));

	  printf ("next_event: %i ev_time: %s", type, ctime (&ev_time));
	}
      last_event = ev_time;
    }
  printf ("done\n\nOK\n");
  return 0;
}
Пример #9
0
double run_laundry(laundry l){
    event current, e;
    double t;

    /*Acumulador del tiempo en funcionamiento*/
    double trunning=0;
    
    int broken = 0, waiting = 0;

    /*Se inicializa el sistema*/
    l = init_laundry(l);
    while(broken <= (l->s)){
        /*Mientras la cantidad de maquinas rotas sea menor
        o igual a la cantidad de repuestos, el sistema puede
        funcionar.       
        */
        current = next_event(l->events_list);
        trunning += get_time(current);
        
        if(get_type(current) == MACHINE_BROKEN){
            /*El evento es una maquina rota, entonces
            se genera un nuevo tiempo de falla para uno
            los repuestos que entra en funcionamiento.
            */
            t = exponential(l->rg, 1./(l->tfail));
            e = create_event(t, MACHINE_BROKEN);
            l->events_list = insert_event(l->events_list, e);
            broken++;

            if(broken <= (l->o)){
                /*Si hay un operario libre, entonces se genera
                un nuevo tiempo de reparacion para la maquina que
                entra al taller.                
                */
                t = exponential(l->rg, 1./(l->trepair));
                e = create_event(t, MACHINE_REPAIRED);
                l->events_list = insert_event(l->events_list, e);
            }
            else{
                /*Si todos los operarios estan ocupados, la maquina
                queda en espera.
                */
                waiting++;
            }
        }
        else{
            /*El evento es una maquina reparada, entonces hay una maquina
            rota menos. Ademas se acaba de liberar un operario, entonces si hay
            maquinas en espera de reparacion, se genera un nuevo tiempo de 
            reparacion.
            */
            broken--;
            if(waiting > 0){
                waiting--;
                t = exponential(l->rg, 1./(l->trepair));
                e = create_event(t, MACHINE_REPAIRED);
                l->events_list = insert_event(l->events_list, e);
            }
        }
        destroy_event(current);
    }
    
    return trunning;
}
Пример #10
0
static void
state_machine_handler(int fd __attribute__((unused)), short event, void *arg)
{
  struct state_data *sd= arg;
  int status;

again:
  switch(sd->ST)
  {
  case 0:
    /* Initial state, start making the connection. */
    status= mysql_real_connect_start(&sd->ret, &sd->mysql, opt_host, opt_user, opt_password, opt_db, opt_port, opt_socket, 0);
    if (status)
      /* Wait for connect to complete. */
      next_event(1, status, sd);
    else
      NEXT_IMMEDIATE(sd, 9);
    break;

  case 1:
    status= mysql_real_connect_cont(&sd->ret, &sd->mysql, mysql_status(event));
    if (status)
      next_event(1, status, sd);
    else
      NEXT_IMMEDIATE(sd, 9);
    break;

  case 9:
    if (!sd->ret)
      fatal(sd, "Failed to mysql_real_connect()");
    NEXT_IMMEDIATE(sd, 10);
    break;

  case 10:
    /* Now run the next query. */
    sd->query_element= query_list;
    if (!sd->query_element)
    {
      /* No more queries, end the connection. */
      NEXT_IMMEDIATE(sd, 40);
    }
    query_list= query_list->next;

    sd->index= sd->query_element->index;
    printf("%d ! %s\n", sd->index, sd->query_element->query);
    status= mysql_real_query_start(&sd->err, &sd->mysql, sd->query_element->query,
                                   strlen(sd->query_element->query));
    if (status)
      next_event(11, status, sd);
    else
      NEXT_IMMEDIATE(sd, 20);
    break;

  case 11:
    status= mysql_real_query_cont(&sd->err, &sd->mysql, mysql_status(event));
    if (status)
      next_event(11, status, sd);
    else
      NEXT_IMMEDIATE(sd, 20);
    break;

  case 20:
    my_free(sd->query_element->query);
    my_free(sd->query_element);
    if (sd->err)
    {
      printf("%d | Error: %s\n", sd->index, mysql_error(&sd->mysql));
      NEXT_IMMEDIATE(sd, 10);
    }
    else
    {
      sd->result= mysql_use_result(&sd->mysql);
      if (!sd->result)
        fatal(sd, "mysql_use_result() returns error");
      NEXT_IMMEDIATE(sd, 30);
    }
    break;

  case 30:
    status= mysql_fetch_row_start(&sd->row, sd->result);
    if (status)
      next_event(31, status, sd);
    else
      NEXT_IMMEDIATE(sd, 39);
    break;

  case 31:
    status= mysql_fetch_row_cont(&sd->row, sd->result, mysql_status(event));
    if (status)
      next_event(31, status, sd);
    else
      NEXT_IMMEDIATE(sd, 39);
    break;

  case 39:
    if (sd->row)
    {
      /* Got a row. */
      unsigned int i;
      printf("%d - ", sd->index);
      for (i= 0; i < mysql_num_fields(sd->result); i++)
        printf("%s%s", (i ? "\t" : ""), (sd->row[i] ? sd->row[i] : "(null)"));
      printf ("\n");
      NEXT_IMMEDIATE(sd, 30);
    }
    else
    {
      if (mysql_errno(&sd->mysql))
      {
        /* An error occured. */
        printf("%d | Error: %s\n", sd->index, mysql_error(&sd->mysql));
      }
      else
      {
        /* EOF. */
        printf("%d | EOF\n", sd->index);
      }
      mysql_free_result(sd->result);
      NEXT_IMMEDIATE(sd, 10);
    }
    break;

  case 40:
    status= mysql_close_start(&sd->mysql);
    if (status)
      next_event(41, status, sd);
    else
      NEXT_IMMEDIATE(sd, 50);
    break;

  case 41:
    status= mysql_close_cont(&sd->mysql, mysql_status(event));
    if (status)
      next_event(41, status, sd);
    else
      NEXT_IMMEDIATE(sd, 50);
    break;

  case 50:
    /* We are done! */
    num_active_connections--;
    if (num_active_connections == 0)
      event_loopbreak();
    break;

  default:
    abort();
  }
}
Пример #11
0
void run_kmp ()
{
  nkmp = 0;
  int cur_c = 0, cur_i = 0;
  __int64 pos_c = 1, pos_i = 0;
  while (pos_c >= str[cur_c].b)
    cur_c++;
  char c_c = str[cur_c].c;
  char c_i = str[cur_i].c;
  int i_vel;
  if (c_c == c_i)
  {
    start_block (pos_c, pos_i + 1, 1);
    i_vel = 1;
  }
  else
  {
    start_block (pos_c, 0, 0);
    i_vel = 0;
  }
  __int64 time = 0;
  add_event (EVENT_CURSOR, str[cur_c].b - pos_c + time);
  add_event (EVENT_IMAGE, str[cur_i].b - pos_i + time);
  while (pos_c < len)
  {
    event e = next_event ();
    __int64 delta = e.time - time;
    time = e.time;
    pos_c += delta;
    pos_i += delta * i_vel;
    while (pos_i >= str[cur_i].b)
      cur_i++;
    while (pos_c >= str[cur_c].b)
      cur_c++;
    char c_c = str[cur_c].c;
    char c_i = str[cur_i].c;
    if (pos_c >= len)
      break;
    end_block (pos_c);
#ifdef _DBG_
    printf ("$%I64d (%d) %I64d (%d)\n", pos_i, cur_i, pos_c, cur_c);
#endif
    while (c_c != c_i && pos_i > 0)
    {
#ifdef _DBG_
      printf ("!jump from %I64d", pos_i - 1);
#endif
      pos_i = get_answer (pos_i - 1);
      cur_i = bin_search (pos_i);
      c_i = str[cur_i].c;
#ifdef _DBG_
      printf (" to %I64d (%d)\n", pos_i, cur_i);
#endif
    }
    if (c_c == c_i)
    {
      start_block (pos_c, pos_i + 1, 1);
      i_vel = 1;
    }
    else
    {
      start_block (pos_c, 0, 0);
      i_vel = 0;
    }
    add_event (EVENT_CURSOR, str[cur_c].b - pos_c + time);
    add_event (EVENT_IMAGE, str[cur_i].b - pos_i + time);
  }
  end_block (len);
}
Пример #12
0
/**
 * The main function of BaseStation for Mongol.
 *
 * Entry point of program. Upon starting with normal mode values set,
 * this function parses any command line arguments, initializes the controller
 * interface (\sa Controller.h), intitializes the robot communication interface
 * (\sa Serial.h), and then enters the main control loop of the program. There,
 * the program basically gathers user input data from the controller, builds a
 * serial packet, and then sends it to the robot. The program waits for
 * confirmation from the robot in the form of a PKT_RDY packet type before
 * looping again.
 */
int
main (int argc, char* argv[])
{
    // Set default values
    m_ctrl_mode = Ctrl_Mode_Keyboard;
    m_comm_mode = Comm_Mode_Offline;
    m_ui_mode   = UI_Mode_Terminal;

    // Parse command line arguements
    parse_args (argc, argv);

    // Initialize SDL (VIDEO flag also initializes event handling)
    print_log ("Initializing controller... ", Log_Level_Med);
    if (!(initCtrl()))
    {
        print_log ("Controller failed to intialize.\n", Log_Level_High);
        quit_basestation ();
    }
    print_log ("Controller Initialized.\n", Log_Level_Med);

    // Initialize serial port (includes looking for HELLO packet
    // If not port name specified, default to /dev/ttyUSB0 (for Linux)
    if (m_comm_mode == Comm_Mode_Online)
    {
        print_log ("Connecting to robot... ", Log_Level_Med);
        if ((ms_comm_device ? init_serial (ms_comm_device) : init_serial ("/dev/ttyUSB0")) < 0)
        {
            print_log ("Failed to connect\n", Log_Level_High);
            m_comm_mode = Comm_Mode_Offline;
            quit_basestation ();
        }
        print_log ("Robot connected.\n", Log_Level_Med);
    }

    Msg out_msg;
    Msg in_msg;
    char intype_buf [128];
    char outtype_buf [128];
    int print_nxt_received = 0;

    // Main program loop
    for(;;)
    {
        next_event (&out_msg);

        if(m_comm_mode == Comm_Mode_Online)
        {
            do
            {
                serial_write (&out_msg);
                usleep (10);
            }
            while (serial_read (&in_msg) ||
                   (in_msg.type != Msg_Type_Ready));

            if (out_msg.type != Msg_Type_Standby)
            {
                type_to_str (intype_buf, out_msg.type);
                printf ("Sent: %s\n", intype_buf);
                type_to_str (outtype_buf, in_msg.type);
                printf ("Received: %s\n", outtype_buf);
            }
        }
    }

    return 0;
}
Пример #13
0
MDB_ASYNC_ST MySQL_Connection::handler(short event) {
	if (mysql==NULL) {
		// it is the first time handler() is being called
		async_state_machine=ASYNC_CONNECT_START;
		myds->wait_until=myds->sess->thread->curtime+mysql_thread___connect_timeout_server*1000;
	}
handler_again:
	proxy_debug(PROXY_DEBUG_MYSQL_PROTOCOL, 6,"async_state_machine=%d\n", async_state_machine);
	switch (async_state_machine) {
		case ASYNC_CONNECT_START:
			connect_start();
			if (async_exit_status) {
				next_event(ASYNC_CONNECT_CONT);
			} else {
				NEXT_IMMEDIATE(ASYNC_CONNECT_END);
			}
			break;
		case ASYNC_CONNECT_CONT:
			if (event) {
				connect_cont(event);
			}
			if (async_exit_status) {
					if (myds->sess->thread->curtime >= myds->wait_until) {
						NEXT_IMMEDIATE(ASYNC_CONNECT_TIMEOUT);
					}
      	next_event(ASYNC_CONNECT_CONT);
			} else {
				NEXT_IMMEDIATE(ASYNC_CONNECT_END);
			}
    break;
			break;
		case ASYNC_CONNECT_END:
			if (!ret_mysql) {
				// always increase the counter
				proxy_error("Failed to mysql_real_connect() on %s:%d , %d: %s\n", parent->address, parent->port, mysql_errno(mysql), mysql_error(mysql));
    		NEXT_IMMEDIATE(ASYNC_CONNECT_FAILED);
			} else {
    		NEXT_IMMEDIATE(ASYNC_CONNECT_SUCCESSFUL);
			}
    	break;
		case ASYNC_CONNECT_SUCCESSFUL:
			__sync_fetch_and_add(&MyHGM->status.server_connections_connected,1);
			__sync_fetch_and_add(&parent->connect_OK,1);
			break;
		case ASYNC_CONNECT_FAILED:
			parent->connect_error(mysql_errno(mysql));
			break;
		case ASYNC_CONNECT_TIMEOUT:
			proxy_error("Connect timeout on %s:%d : %llu - %llu = %llu\n",  parent->address, parent->port, myds->sess->thread->curtime , myds->wait_until, myds->sess->thread->curtime - myds->wait_until);
			parent->connect_error(mysql_errno(mysql));
			break;
		case ASYNC_CHANGE_USER_START:
			change_user_start();
			if (async_exit_status) {
				next_event(ASYNC_CHANGE_USER_CONT);
			} else {
				NEXT_IMMEDIATE(ASYNC_CHANGE_USER_END);
			}
			break;
		case ASYNC_CHANGE_USER_CONT:
			assert(myds->sess->status==CHANGING_USER_SERVER);
			change_user_cont(event);
			if (async_exit_status) {
				next_event(ASYNC_CHANGE_USER_CONT);
			} else {
				NEXT_IMMEDIATE(ASYNC_CHANGE_USER_END);
			}
			break;
		case ASYNC_CHANGE_USER_END:
			if (ret_bool) {
				fprintf(stderr,"Failed to mysql_change_user()");
				NEXT_IMMEDIATE(ASYNC_CHANGE_USER_FAILED);
			} else {
				NEXT_IMMEDIATE(ASYNC_CHANGE_USER_SUCCESSFUL);
			}
			break;
		case ASYNC_CHANGE_USER_SUCCESSFUL:
			break;
		case ASYNC_CHANGE_USER_FAILED:
			break;
		case ASYNC_PING_START:
			ping_start();
			if (async_exit_status) {
				next_event(ASYNC_PING_CONT);
			} else {
				NEXT_IMMEDIATE(ASYNC_PING_END);
			}
			break;
		case ASYNC_PING_CONT:
			assert(myds->sess->status==PINGING_SERVER);
			ping_cont(event);
			if (async_exit_status) {
				next_event(ASYNC_PING_CONT);
			} else {
				NEXT_IMMEDIATE(ASYNC_PING_END);
			}
			break;
		case ASYNC_PING_END:
			if (interr) {
				NEXT_IMMEDIATE(ASYNC_PING_FAILED);
			} else {
				NEXT_IMMEDIATE(ASYNC_PING_SUCCESSFUL);
			}
			break;
		case ASYNC_PING_SUCCESSFUL:
			break;
		case ASYNC_PING_FAILED:
			break;
		case ASYNC_QUERY_START:
			real_query_start();
			__sync_fetch_and_add(&parent->queries_sent,1);
			__sync_fetch_and_add(&parent->bytes_sent,query.length);
			myds->sess->thread->status_variables.queries_backends_bytes_sent+=query.length;
			if (async_exit_status) {
				next_event(ASYNC_QUERY_CONT);
			} else {
#ifdef PROXYSQL_USE_RESULT
				NEXT_IMMEDIATE(ASYNC_USE_RESULT_START);
#else
				NEXT_IMMEDIATE(ASYNC_STORE_RESULT_START);
#endif
			}
			break;
		case ASYNC_QUERY_CONT:
			real_query_cont(event);
			if (async_exit_status) {
				next_event(ASYNC_QUERY_CONT);
			} else {
#ifdef PROXYSQL_USE_RESULT
				NEXT_IMMEDIATE(ASYNC_USE_RESULT_START);
#else
				NEXT_IMMEDIATE(ASYNC_STORE_RESULT_START);
#endif
			}
			break;
		case ASYNC_STORE_RESULT_START:
			if (mysql_errno(mysql)) {
				NEXT_IMMEDIATE(ASYNC_QUERY_END);
			}
			store_result_start();
			if (async_exit_status) {
				next_event(ASYNC_STORE_RESULT_CONT);
			} else {
				NEXT_IMMEDIATE(ASYNC_QUERY_END);
			}
			break;
		case ASYNC_STORE_RESULT_CONT:
			store_result_cont(event);
			if (async_exit_status) {
				next_event(ASYNC_STORE_RESULT_CONT);
			} else {
				NEXT_IMMEDIATE(ASYNC_QUERY_END);
			}
			break;
		case ASYNC_USE_RESULT_START:
			if (mysql_errno(mysql)) {
				NEXT_IMMEDIATE(ASYNC_QUERY_END);
			}
			mysql_result=mysql_use_result(mysql);
			if (mysql_result==NULL) {
				NEXT_IMMEDIATE(ASYNC_QUERY_END);
			} else {
				MyRS=new MySQL_ResultSet(&myds->sess->client_myds->myprot, mysql_result, mysql);
				async_fetch_row_start=false;
				NEXT_IMMEDIATE(ASYNC_USE_RESULT_CONT);
			}
			break;
		case ASYNC_USE_RESULT_CONT:
			if (async_fetch_row_start==false) {
				async_exit_status=mysql_fetch_row_start(&mysql_row,mysql_result);
				async_fetch_row_start=true;
			} else {
				async_exit_status=mysql_fetch_row_cont(&mysql_row,mysql_result, mysql_status(event, true));
			}
			if (async_exit_status) {
				next_event(ASYNC_USE_RESULT_CONT);
			} else {
				async_fetch_row_start=false;
				if (mysql_row) {
					unsigned int br=MyRS->add_row(mysql_row);
					__sync_fetch_and_add(&parent->bytes_recv,br);
					myds->sess->thread->status_variables.queries_backends_bytes_recv+=br;
					NEXT_IMMEDIATE(ASYNC_USE_RESULT_CONT);
				} else {
					MyRS->add_eof();
					NEXT_IMMEDIATE(ASYNC_QUERY_END);
				}
			}
			break;
		case ASYNC_QUERY_END:
			break;
		case ASYNC_SET_AUTOCOMMIT_START:
			set_autocommit_start();
			if (async_exit_status) {
				next_event(ASYNC_SET_AUTOCOMMIT_CONT);
			} else {
				NEXT_IMMEDIATE(ASYNC_SET_AUTOCOMMIT_END);
			}
			break;
		case ASYNC_SET_AUTOCOMMIT_CONT:
			set_autocommit_cont(event);
			if (async_exit_status) {
				next_event(ASYNC_SET_AUTOCOMMIT_CONT);
			} else {
				NEXT_IMMEDIATE(ASYNC_SET_AUTOCOMMIT_END);
			}
			break;
		case ASYNC_SET_AUTOCOMMIT_END:
			if (ret_bool) {
				NEXT_IMMEDIATE(ASYNC_SET_AUTOCOMMIT_FAILED);
			} else {
				NEXT_IMMEDIATE(ASYNC_SET_AUTOCOMMIT_SUCCESSFUL);
			}
			break;
		case ASYNC_SET_AUTOCOMMIT_SUCCESSFUL:
			break;
		case ASYNC_SET_AUTOCOMMIT_FAILED:
			fprintf(stderr,"%s\n",mysql_error(mysql));
			break;
		case ASYNC_SET_NAMES_START:
			set_names_start();
			if (async_exit_status) {
				next_event(ASYNC_SET_NAMES_CONT);
			} else {
				NEXT_IMMEDIATE(ASYNC_SET_NAMES_END);
			}
			break;
		case ASYNC_SET_NAMES_CONT:
			set_names_cont(event);
			if (async_exit_status) {
				next_event(ASYNC_SET_NAMES_CONT);
			} else {
				NEXT_IMMEDIATE(ASYNC_SET_NAMES_END);
			}
			break;
		case ASYNC_SET_NAMES_END:
			if (interr) {
				NEXT_IMMEDIATE(ASYNC_SET_NAMES_FAILED);
			} else {
				NEXT_IMMEDIATE(ASYNC_SET_NAMES_SUCCESSFUL);
			}
			break;
		case ASYNC_SET_NAMES_SUCCESSFUL:
			break;
		case ASYNC_SET_NAMES_FAILED:
			fprintf(stderr,"%s\n",mysql_error(mysql));
			break;
		case ASYNC_INITDB_START:
			initdb_start();
			if (async_exit_status) {
				next_event(ASYNC_INITDB_CONT);
			} else {
				NEXT_IMMEDIATE(ASYNC_INITDB_END);
			}
			break;
		case ASYNC_INITDB_CONT:
			initdb_cont(event);
			if (async_exit_status) {
				next_event(ASYNC_INITDB_CONT);
			} else {
				NEXT_IMMEDIATE(ASYNC_INITDB_END);
			}
			break;
		case ASYNC_INITDB_END:
			if (interr) {
				NEXT_IMMEDIATE(ASYNC_INITDB_FAILED);
			} else {
				NEXT_IMMEDIATE(ASYNC_INITDB_SUCCESSFUL);
			}
			break;
		case ASYNC_INITDB_SUCCESSFUL:
			break;
		case ASYNC_INITDB_FAILED:
			fprintf(stderr,"%s\n",mysql_error(mysql));
			break;
		default:
			assert(0); //we should never reach here
			break;
		}
	return async_state_machine;
}
Пример #14
0
bool process_events()
{
	OsEvent event;
	bool exit = false;
	InputManager* im = device()->input_manager();

	while(next_event(event))
	{
		if (event.type == OsEvent::NONE) continue;

		switch (event.type)
		{
			case OsEvent::TOUCH:
			{
				const OsTouchEvent& ev = event.touch;
				switch (ev.type)
				{
					case OsTouchEvent::POINTER:
						im->touch()->set_button_state(ev.pointer_id, ev.pressed);
						break;
					case OsTouchEvent::MOVE:
						im->touch()->set_axis(ev.pointer_id, vector3(ev.x, ev.y, 0.0f));
						break;
					default:
						CE_FATAL("Oops, unknown touch event type");
						break;
				}
				break;
			}
			case OsEvent::MOUSE:
			{
				const OsMouseEvent& ev = event.mouse;
				switch (ev.type)
				{
					case OsMouseEvent::BUTTON:
						im->mouse()->set_button_state(ev.button, ev.pressed);
						break;
					case OsMouseEvent::MOVE:
						im->mouse()->set_axis(0, vector3(ev.x, ev.y, 0.0f));
						break;
					case OsMouseEvent::WHEEL:
						im->mouse()->set_axis(1, vector3(ev.wheel, 0.0f, 0.0f));
						break;
					default:
						CE_FATAL("Oops, unknown mouse event type");
						break;
				}
				break;
			}
			case OsEvent::KEYBOARD:
			{
				const OsKeyboardEvent& ev = event.keyboard;
				im->keyboard()->set_button_state(ev.button, ev.pressed);
				break;
			}
			case OsEvent::METRICS:
			{
				const OsMetricsEvent& ev = event.metrics;
				device()->update_resolution(ev.width, ev.height);
				bgfx::reset(ev.width, ev.height, BGFX_RESET_VSYNC);
				break;
			}
			case OsEvent::EXIT:
			{
				exit = true;
				break;
			}
			case OsEvent::PAUSE:
			{
				device()->pause();
				break;
			}
			case OsEvent::RESUME:
			{
				device()->unpause();
				break;
			}
			default:
			{
				CE_FATAL("Unknown Os Event");
				break;
			}
		}
	}

	return exit;
}
/*
 * The heart of the algorithm:  Compute the minimum value of the
 * integral term of the metric by considering all critical events.
 * This also returns the theta* and event associated with the minimum.
 */
double h_t0min(TURN_REP* f, TURN_REP* g,
	       double hc0, double slope, double alpha, int d_update,
               double *theta_star_rtn, EVENT_REC* e_rtn,
               double *hc0_err_rtn, double *slope_err_rtn)
{
    int left_to_update;                 /* # disconts left until update */
    double metric2, min_metric2;        /* d^2 and d^2_min thus far */
    double theta_star, min_theta_star;  /* theta* and theta*_min thus far */
    double last_t;                      /* t of last iteration */
    double hc0_err, slope_err;          /* error mags discovered on update */
    EVENT_REC e;                        /* current event */
    EVENT_REC min_e;                    /* event of d^2_min thus far */

    static EVENT_REC init_min_e = {0,0,0};  /* implicit first event */

    /*
     * At t = 0, theta_star is just alpha, and the min
     * metric2 seen so far is hc0 - min_theta_star^2.
     * Also, no error has been seen.
     */
    min_theta_star = alpha;
    min_metric2 = hc0 - min_theta_star * min_theta_star;
    min_e = init_min_e;
    last_t = hc0_err = slope_err = 0;
    /*
     * Compute successive hc_i0's by incremental update
     * at critical events as described in the paper.
     */
    left_to_update = d_update;
    while (n_events > 0)
    {
        e = next_event();
        hc0 += (e.t - last_t) * slope;
        theta_star = alpha - 2 * M_PI * e.t;
        metric2 = hc0 - theta_star * theta_star;
        if (metric2 < min_metric2)
        {
            min_metric2 = metric2;
            min_theta_star = theta_star;
            min_e = e;
        }
        /*
         * Update slope, last t, and put next event for this g
         * discontinuity in the heap.
         */
        slope += 2*(tr_theta(f, e.fi-1) - tr_theta(f, e.fi))
                  *(tr_theta(g, e.gi-1) - tr_theta(g, e.gi));
        last_t = e.t;
        add_event(f, g, e.fi+1, e.gi);
        /*
         * Re-establish hc0 and slope now and then
         * to reduce numerical error.  If d_update is 0, do nothing.
         * Note we don't update if an event is close, as this
         * causes numerical ambiguity.  The test number could be much
         * smaller, but why tempt Murphey?  We force an update on last
         * event so there's always at least one.
         */
        if (d_update &&
	    (n_events == 0 ||
            --left_to_update <= 0 && e.t - last_t > 0.001 && next_t() - e.t > 0.001)) {

            double rihc0, rislope, dhc0, dslope;

            reinit_vals(f, g, e.fi, e.gi, &rihc0, &rislope);
            dhc0 = hc0 - rihc0;
            dslope = slope - rislope;
            if (fabs(dhc0) > fabs(hc0_err))
              hc0_err = dhc0;
            if (fabs(dslope) > fabs(slope_err))
              slope_err = dslope;
            hc0 = rihc0;
            slope = rislope;
            left_to_update = d_update;
        }
    }
    /*
     * Set up return values.
     */
    *theta_star_rtn = min_theta_star;
    *e_rtn = min_e;
    *hc0_err_rtn = hc0_err;
    *slope_err_rtn = slope_err;
    return(min_metric2);
}
Пример #16
0
void t_pgrid::run()
{
    bool quit= false;
    
    setvbuf(stdout, 0, _IONBF, 0);
    
    SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
    SDL_WM_SetCaption("pgrid", "pgrid");
    
    lastmillis= curmillis= SDL_GetTicks();
    SDL_ShowCursor(0);
    SDL_EnableUNICODE(true);
    
    gui= new flux_gui();
    
    bool guimouse= false;
    
    while(!quit)
    {
	lastframephystime= physicstime;
	lastmillis= curmillis;
	curmillis= SDL_GetTicks();
	
	SDL_Event event;
	while(SDL_PollEvent(&event))
	{
	    switch(event.type)
	    {
		case SDL_KEYDOWN:
		case SDL_KEYUP:
		{
		    if(event.key.keysym.sym==SDLK_ESCAPE) quit= true;
		    
		    if(wnd_getkbdfocus()!=NOWND)
		    {
			flux_keyboard_event(event.type==SDL_KEYDOWN, event.key.keysym.sym, event.key.keysym.unicode&0x7F);
		    }
		    else
		    {
			current_workspace()->keyboard_event(event.key);
			editor->keyboard_event(event.key);
			for(t_dyninputhandler_list::iterator i= dyninputhandlers.begin(); i!=dyninputhandlers.end(); i++)
			    (*i)->keyboard_event(event.key);
		    }
		    
		    keystate[event.key.keysym.sym]= (event.key.state==SDL_PRESSED? 1: 0);
		    break;
		}
		
		case SDL_MOUSEMOTION:
		    flux_mouse_move_event(event.motion.xrel, event.motion.yrel);
		    
		    if( find_prim_pos(event.motion.x, event.motion.y, true) || 
			find_mouse_handler(event.motion.x, event.motion.y) )
			guimouse= true;
		    else
		    {
			guimouse= false;
			mouse.x= event.motion.x;
			mouse.y= event.motion.y;
			mouse.buttons= event.motion.state;
			current_workspace()->mouse_motion_event(event.motion);
			editor->mouse_motion_event(event.motion);
			for(t_dyninputhandler_list::iterator i= dyninputhandlers.begin(); i!=dyninputhandlers.end(); i++)
			    (*i)->mouse_motion_event(event.motion);
		    }
		    break;
		
		case SDL_MOUSEBUTTONUP:
		case SDL_MOUSEBUTTONDOWN:
		{
		    int b= event.button.button;
		    int fluxbutton= (b==SDL_BUTTON_RIGHT? 2: b==SDL_BUTTON_MIDDLE? 3: b)-1;
		    flux_mouse_button_event(fluxbutton, event.type==SDL_MOUSEBUTTONDOWN);
		    
		    if( find_prim_pos(event.button.x, event.button.y, true) || 
			find_mouse_handler(event.button.x, event.button.y) )
		    {
		    	guimouse= true;
		    }
		    else
		    {
			guimouse= false;
			wnd_setkbdfocus(NOWND);
			if(event.type==SDL_MOUSEBUTTONUP)
			    mouse.buttons&= ~(SDL_BUTTON(event.button.button));
			else
			    mouse.buttons|= SDL_BUTTON(event.button.button);
			mouse.x= event.button.x;
			mouse.y= event.button.y;
			current_workspace()->mouse_button_event(event.button);
			editor->mouse_button_event(event.button);
			for(t_dyninputhandler_list::iterator i= dyninputhandlers.begin(); i!=dyninputhandlers.end(); i++)
			    (*i)->mouse_button_event(event.button);
		    }
		    break;
		}

		case SDL_QUIT:
		    quit= true;
		    break;
		
		case SDL_VIDEORESIZE:
		{
		    SDL_Surface *surf= SDL_SetVideoMode(event.resize.w, event.resize.h, 0, SDL_OPENGL|SDL_RESIZABLE);
		    if(!surf) break;
		    screen.sdl_surface= surf;
		    screen.gl_init(event.resize.w, event.resize.h);
		    current_workspace()->centerimage();
		    break;
		}
		
		case SDL_ACTIVEEVENT:
		{
		    if(event.active.state&SDL_APPINPUTFOCUS)
		    {
			hasinputfocus= event.active.gain;
			SDL_ShowCursor(!hasinputfocus);
		    }
		    if(event.active.state&SDL_APPMOUSEFOCUS)
		    	hasmousefocus= event.active.gain;
		    break;
		}
		
		case SDL_VIDEOEXPOSE:
		{
		    if(!hasinputfocus)
		    {
    			glClear(GL_DEPTH_BUFFER_BIT);
			current_workspace()->render();
			SDL_GL_SwapBuffers();
			checkglerror();
		    }
		    break;
		}
	    }
	}
	
	int x, y;
	SDL_GetMouseState(&x, &y);
	mousepos.x= x; mousepos.y= y;

	SDL_GetRelativeMouseState(&x, &y);
	mousevel.x= x; mousevel.y= y;
	mousevel.mul( 1000.0/(curmillis-lastmillis) );
	
	current_workspace()->image->frame_tick((curmillis-lastmillis)*0.001);
	runphysics();
	

    	if(hasinputfocus)
	{
	    glClear(GL_DEPTH_BUFFER_BIT);
	    //~ screen.setperspective();
	    current_workspace()->render();
	    if(hasmousefocus && !guimouse) editor->render();

#if 1
	    next_event();
	    //~ aq_exec();
	    run_timers();
	    
	    glMatrixMode(GL_MODELVIEW);
	    glPushMatrix();
	    glLoadIdentity();
	    
	    glMatrixMode(GL_PROJECTION);
	    glPushMatrix();
	    glLoadIdentity();
	    glOrtho(0, screen.width,screen.height, 0, -1000, 1000);

	    glDisable(GL_DEPTH_TEST);
	    glEnable(GL_BLEND);
	    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	    //~ glEnable(GL_POINT_SMOOTH);
	    //~ glPointSize(1.0);
	    
	    //~ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
	    //~ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
	    glColor3f(1,1,1);
	    glDisable(GL_TEXTURE_2D);
	    
	    redraw_rect(&viewport);
	    //~ cliptext(0,0,0,0);
	    update_rect(&viewport);

	    glEnable(GL_DEPTH_TEST);
	    glDisable(GL_BLEND);
	    
	    glMatrixMode(GL_PROJECTION);
	    glPopMatrix();
	    glMatrixMode(GL_MODELVIEW);
	    glPopMatrix();
#endif
	    
	    gui->tick( (curmillis-lastmillis)*0.001 );
	    
	    if(guimouse) { glMatrixMode(GL_TEXTURE); glLoadIdentity(); glDisable(GL_DEPTH_TEST); redraw_cursor(); }
	    
	    SDL_GL_SwapBuffers();
	    checkglerror();
	}
	
	
	int delay= 10 - (curmillis-lastmillis);
	if(!hasinputfocus) SDL_Delay(100);
	if(delay>0) SDL_Delay(delay);
    }
    
    SDL_WM_GrabInput(SDL_GRAB_OFF);
    
    delete gui;
    gui= 0;
}
Пример #17
0
   void Scheduler::run()
   {
      avlock.lock();
      auto event = next_event();
      avlock.unlock();

      if (!is_active)
      {
         sync_sleep(0.01);
         return;
      }

      show_info();

      switch (event)
      {
         case EventHandler::Event::Quit:
            is_active = false;
            video_thread_active = false;
            audio_thread_active = false;
            return;

         case EventHandler::Event::Pause:
            pause_toggle();
            break;

         case EventHandler::Event::SeekBack10:
            perform_seek(-3.0);
            break;

         case EventHandler::Event::SeekForward10:
            perform_seek(3.0);
            break;

         case EventHandler::Event::SeekBack60:
            perform_seek(-30.0);
            break;

         case EventHandler::Event::SeekForward60:
            perform_seek(30.0);
            break;

         case EventHandler::Event::Fullscreen:
            if (video_thread_active)
               video->toggle_fullscreen();
            break;

         case EventHandler::Event::None:
            break;

         default:
            throw std::runtime_error("Unknown event popped up :V\n");
      }

      if (is_paused)
      {
         sync_sleep(0.01);
         return;
      }

      Packet pkt;

      Packet::Type type = file->packet(pkt);

      switch(type)
      {
         case Packet::Type::Error:
            is_active = false;
            // Signal to threads that there won't be any more data.
            aud_pkt_queue.finalize();
            vid_pkt_queue.finalize();
            return;
            
         case Packet::Type::None:
            return;

         case Packet::Type::Audio:
            while (aud_pkt_queue.size() > 16 && (vid_pkt_queue.size() > 16 || !has_video))
               aud_pkt_queue.wait();

            aud_pkt_queue.push(std::move(pkt));
            break;

         case Packet::Type::Video:
            while (vid_pkt_queue.size() > 16 && (aud_pkt_queue.size() > 16 || !has_audio))
               vid_pkt_queue.wait();

            vid_pkt_queue.push(std::move(pkt));
            break;

         case Packet::Type::Subtitle:
            while (sub_pkt_queue.size() > 64 && (aud_pkt_queue.size() > 16 || !has_audio) && (vid_pkt_queue.size() > 16 || !has_video))
               sub_pkt_queue.wait();

            sub_pkt_queue.push(std::move(pkt));
            break;

         default:
            throw std::runtime_error("What kind of package is this? o.o\n");
      }
   }