Ejemplo n.º 1
0
int
main()
{
    st_thread_t thread;
    int rc;
    int i, j, s;

    arg = -1;
    res = -1;
    st_init();
    for(i = 0; i < 10; i++) {
        s = 0;
        for(j = 0; j < 10000; j++) {
            res = -1;
            arg = j;
            thread = st_thread_create(thread_routine, NULL, 1, 0);
            st_sleep(0);
            while(res < 0)
                st_sleep(0);
            s += res;
            st_thread_join(thread, NULL);
            arg = -1;
        }
    }
    printf("%d\n", s);
    return 0;
}
Ejemplo n.º 2
0
void *
thread_routine(void *dummy)
{
        while(arg < 0) {
            st_sleep(0);
        }
        res = arg;
        st_sleep(0);
}
Ejemplo n.º 3
0
void
accept_connection(int fd)
{
    struct sockaddr_in from;
    st_netfd_t st_fd,fd2;
    int fromlen = sizeof(from);
    
    if((st_fd = st_netfd_open_socket(fd)) == NULL)
      {perror("st_netfd_open_socket") ; exit(1);}
    
    while(1) {
        fd2 = st_accept(st_fd,(struct sockaddr *)&from, &fromlen, -1);
        if(fd2 == NULL) {
            if(errno == EINTR) {
              continue;
            } else {
                perror("accept");
                st_sleep(0);
                continue;
            }
        }

        if(st_thread_create(handle_connection, (void *)fd2,0,0) == NULL){
            perror("st_thread_create");
            exit(1);
        }
    }
}
Ejemplo n.º 4
0
/**
 * Handle session for Test players.
 */
void
handle_session( const int thread_id )
{
    hoxLog(LOG_INFO, "%s: [#%d]: ENTER.", __FUNCTION__, thread_id);

    TestPlayer_SPtr player;
    Game*           game = NULL;  // The "assigned" game.

    for (;;)
    {
        if ( player )
        {
            Manager::instance()->onPlayerDisconnected( player, game );
            player.reset();
        }

        game = NULL;
        player = Manager::instance()->createTestPlayer( thread_id, game );
        if ( ! player )
        {
            hoxLog(LOG_DEBUG, "%s: [#%d] waiting for game...", __FUNCTION__, thread_id);
            st_sleep( 60 /* in seconds */ );
            continue;
        }

        try
        {
            player->run();
            st_sleep( 60 /* seconds */ ); // Wait before continue.
        }
        catch (std::runtime_error& ex)
        {
            hoxLog(LOG_WARN, "%s: [#%d] caught runtime exception [%s].",
                    __FUNCTION__, thread_id, ex.what());
        }
    }

    // Cleanup again just to be sure!
    if ( player )
    {
        Manager::instance()->onPlayerDisconnected( player, game );
    }

    hoxLog(LOG_INFO, "%s: [#%d]: END.", __FUNCTION__, thread_id);
}
Ejemplo n.º 5
0
void run_actual_probes(void)
{
  thread_count = 0;
  st_usleep(1); //force context switch so timers will work
  g_hash_table_foreach(cache, add_probe, NULL);
  while (thread_count) {
    st_sleep(1);
  }
}
Ejemplo n.º 6
0
void _peer_simulate_request(const peer_index_t index) {
  struct peer_info *peer_info;
  peer_info = &peer_list[index];

  // 模拟写入一个 RPC 包
  st_sleep(1);

  peer_request(peer_info->name, "default.ping 于默认设置当中", "hold for 10s!是男人就坚持10秒钟");
}
Ejemplo n.º 7
0
Archivo: test.c Proyecto: zgbkny/ctoolx
/* ARGSUSED */
static void *flush_acclog_buffer(void *arg)
{
  for ( ; ; ) {
    st_sleep(ACCLOG_FLUSH_INTERVAL);
    logbuf_flush();
  }

  /* NOTREACHED */
  return NULL;
}
Ejemplo n.º 8
0
void
AIPlayer::_playOneGame( bool& bSessionExpired )
{
    hoxTableInfo tableInfo;
    this->openNewTable( tableInfo, _myRole );

    MoveList moves;  /* just an empty list */
    if ( _engine.get() ) _engine->initGame("" /* fen */, moves );

    const int nTimeout         = (5 * 60); // NOTE: 5-minute timeout.
    bool      bKeepAliveNeeded = false;

    while ( ! (bSessionExpired = _isSessionExpired()) )
    {
        hoxCommand inCommand;  // Incoming command from the server.
        try
        {
            if ( bKeepAliveNeeded )
            {
                hoxLog(LOG_DEBUG, "%s: (%s) Sending Keep-Alive...", __FUNCTION__, m_id.c_str());
                this->sendKeepAlive();
                bKeepAliveNeeded = false;
            }
            this->readIncomingCommand( inCommand, nTimeout );
        }
        catch ( const TimeoutException& ex )
        {
            hoxLog(LOG_DEBUG, "%s: (%s) Timeout reading incoming command. (%s).",
                __FUNCTION__, m_id.c_str(), ex.what());
            bKeepAliveNeeded = true;
            continue;
        }

        const std::string sInType    = inCommand.m_type;
        const std::string sInContent = inCommand["content"];

        hoxLog(LOG_DEBUG, "%s: (%s) Received command [%s: %s].", __FUNCTION__,
            m_id.c_str(), inCommand.m_type.c_str(), sInContent.c_str());

        if      ( sInType == "E_JOIN" ) _handle_E_JOIN( sInContent );
        else if ( sInType == "MOVE" )   _handle_MOVE( sInContent );
        else if ( sInType == "DRAW" )   _handle_DRAW( sInContent );
        else if ( sInType == "E_END" )
        {
            if ( _handle_E_END( sInContent ) )  // my game ended?
            {
                break;
            }
        }
    } // while ( ... )

    st_sleep( 10 /* seconds */ ); // Take a break before playing again.
    this->leaveCurrentTable();
}
Ejemplo n.º 9
0
void
AIPlayer::_handle_DRAW( const std::string& sInContent )
{
    std::string tableId, playerId;

    hoxCommand::Parse_InCommand_DRAW( sInContent,
                                      tableId, playerId );
    hoxLog(LOG_DEBUG, "%s: (%s) Received [DRAW: %s %s].", __FUNCTION__,
        m_id.c_str(), tableId.c_str(), playerId.c_str());
    st_sleep( 10 /* in seconds */ );
    this->sendDraw( tableId );
}
Ejemplo n.º 10
0
void *ping(void *s)
{
    thread_init *p = s;  /* p has the proper type instead of void */
    int i;
    int sleep_time;
    char sync[1] = {'S'};
    unsigned int rand_seed = p->my_seed;

    for (i = 0; i < p->count; i++)
    {
        sleep_time = 1 + (rand_r(&rand_seed) % p->max_sleep);
        printf("%s (Delay %d seconds before & after Pong thread)\n", p->my_call, sleep_time);
        st_sleep(sleep_time);
        BB_put(sync);
        st_sleep(sleep_time);   /* give pong a chance to run */
    }
    quit = true;
    printf("Ping exiting\n");
    BB_put(sync);
    fflush(stdout);
    st_thread_exit(NULL);
}
Ejemplo n.º 11
0
std::string
AIPlayer::generateNextMove()
{
    std::string sMove;
    if ( _engine.get() )
    {
        ++_moveNumber;
        st_sleep( _getTimeBetweenMoves() /* in seconds */ );
        sMove = _engine->generateMove();
    }

    return sMove;
}
Ejemplo n.º 12
0
/**
 * AI thread.
 */
void*
AI_Player_thread( void* arg )
{
    std::auto_ptr<hoxAIConfig> pAIConfig( (hoxAIConfig*) arg );

    const std::string sPIDs = hoxUtil::joinElements<hoxStringVector>(pAIConfig->pids);
    hoxLog(LOG_INFO,  "%s: pids      = [%s]", __FUNCTION__, sPIDs.c_str() );
    hoxLog(LOG_DEBUG, "%s: password  = [%s]", __FUNCTION__, pAIConfig->password.c_str() );
    hoxLog(LOG_DEBUG, "%s: ai_engine = [%s]", __FUNCTION__, pAIConfig->engine.c_str() );
    hoxLog(LOG_DEBUG, "%s: ai_role   = [%s]", __FUNCTION__, pAIConfig->role.c_str() );
    hoxLog(LOG_DEBUG, "%s: ai_depth  = [%d]", __FUNCTION__, pAIConfig->depth );

    size_t      pindex = 9999;  /* The index of the chosen PID.
                                 * Note; Use large value to use 1st pid.
                                 */
    for (;;)
    {
        // Choose a PID from the list (in a round-robin scheme).
        ++pindex;
        if ( pindex >= pAIConfig->pids.size() ) pindex = 0;
        const std::string pid = pAIConfig->pids[pindex];
        
        // Run the AI Player under the chosen PID.
        try
        {
            hoxLog(LOG_INFO, "%s: AI [%s] STARTED.", __FUNCTION__, pid.c_str());
            AIPlayer_SPtr player( new AIPlayer(pid, pAIConfig->password, pAIConfig->role) );

            if ( ! player->loadAIEngine( pAIConfig->engine, pAIConfig->depth ) )
            {
                hoxLog(LOG_ERROR, "%s: Failed to load AI [%s].", __FUNCTION__, pAIConfig->engine.c_str());
                break;   // get out of here!!!
            }

            player->run();
            hoxLog(LOG_INFO, "%s: AI [%s] ENDED.", __FUNCTION__, pid.c_str());

            // Wait for a while before logging in again.
            st_sleep( 60 /* in seconds */ );
        }
        catch (std::runtime_error& ex)
        {
            hoxLog(LOG_WARN, "%s: Caught runtime exception [%s].", __FUNCTION__, ex.what());
        }
    }

    hoxLog(LOG_INFO, "%s: [%s] END.", __FUNCTION__, sPIDs.c_str());
    return NULL;
}
Ejemplo n.º 13
0
int
main()
{
    int n;
    st_thread_t thread;

    st_init();
    n = 0;
    thread = st_thread_create(thread_routine, NULL, 1, 4096);
    inc_n();

    while(1)
        st_sleep(1);
    return 0;
}
Ejemplo n.º 14
0
static void *read_queue(void *data)
{
  struct q_info *q = (struct q_info *)data;
extern int forever;
static char path[PATH_MAX];
  G_CONST_RETURN gchar *filename;
  GDir *dir;
 
  q->fatal = 0;
  //sprintf(path, "%s/%s/new", OPT_ARG(SPOOLDIR), q->name);
  strcpy(path, OPT_ARG(SPOOLDIR));
  strcat(path, "/");
  strcat(path, q->name);
  strcat(path, "/new");
  if (debug > 3) { LOG(LOG_DEBUG, "reading queue %s", path); }
  dir = g_dir_open (path, 0, NULL);
  while ((filename = g_dir_read_name(dir)) != NULL && !q->fatal && forever) {
    char buffer[PATH_MAX];
    struct thr_data *td;
 
    sprintf(buffer, "%s/%s", path, filename);
    td = g_malloc0(sizeof(struct thr_data));
    td->q = q;
    td->filename = strdup(buffer);
#ifdef USE_ST
    if (st_thread_create(push, td, 0, 0) == NULL) { 
      LOG(LOG_WARNING, "couldn't create thread");
      st_sleep(1);
    } else {
      q->thread_count++;
      thread_count++;
    }
    while (q->thread_count >= q->maxthreads) {
      st_usleep(10000); /* 10 ms */
    }
#else
    push(td);
#endif
  }
  g_dir_close(dir);
#ifdef USE_ST
  thread_count--;
#endif
  return NULL;
}
Ejemplo n.º 15
0
void *
thread_routine(void *dummy)
{
    st_thread_t thread;
    int k;
    while(1) {
        st_sleep(0);
        thread = st_thread_create(thread_routine, NULL, 1, 4096);
        if(thread == NULL) {
            printf("%d\n", n);
            abort();
        }
        k = inc_n();
        if(k % 100 == 0) {
            printf("%d\n", k);
        }
    }
}
Ejemplo n.º 16
0
void *_interconnect_to_peers(void *arg) {
  // TODO: 通过延时来等待其它结点完成侦听。将来要改
  st_sleep(1);

  int i;

  LOG("[%d] 准备向 %d 个 Peer 建立互联\n", self_index, peer_count);

  for (i = 0; i < peer_count; i++) {
    if (i != self_index)
      if (_peer_connect(i) != 0)
        ERR("[%d] failed to connect to peer #%d: %s\n", self_index, i, strerror(errno));
  }

  for (i = 0; i < peer_count; i++) {
    if (i != self_index)
      _peer_simulate_request(i);
  }

  LOG("[%d] 互联完毕\n", self_index);

  return 0;
}
Ejemplo n.º 17
0
void *inputProcessing(void *s){
	thread_Producer_Consumer_init *p = s;
	char inputReceiver = 0;
	printf("%s\n%s\n%s\n",ruler,"Welcome to Duo's HW4 ([email protected]) ",ruler);	
	printf("Thread_1: inputProcessing \n");
	printf("Please Enter: \n");
	
	while (1) {
		if (fscanf(stdin, "%1c", &inputReceiver)==EOF) {
			inputReceiver = EOF;
		}
		depositCirBuf(p->buffer_P, inputReceiver); //Semaphore and mutex included
		if (inputReceiver==EOF) {
			break;
		}
		if (inputReceiver=='\n') {
			st_sleep(WAIT_TIME);
			printf("Please Continue to Enter: \n");
		}
	}
	printf("Thread 1: inputProcessing Existing\n");
	st_thread_exit(NULL);	
}
Ejemplo n.º 18
0
void *
handle_connection(void *fd2)
{
    int rc, n, len;
    int ffd;
    char *buf, *fn;
    int i;

    st_netfd_t fd = (st_netfd_t)fd2;

    buf = malloc(4096);
    rc = 0;

 again:
    rc += st_read(fd, buf + rc, 4096 - rc,-1);
    if(rc < 0) { perror("st_read"); goto fail; }

    if(rc < 4)
        goto fail;

    if(memcmp(buf, "GET ", 4) != 0)
        goto fail;

    for(i = 5; i < rc; i++)
        if(buf[i] == ' ' || buf[i] == '\r' || buf[i] == '\n')
            break;
    if(i == rc && rc < 4096)
        goto again;

    len = strlen(root);

    fn = malloc(len + 1 + i - 5 + 12);
    strcpy(fn, root);
    memcpy(fn + len, buf + 5, i - 5);

    if(buf[i - 1] == '/')
        strcpy(fn + len + i - 5, "index.html");
    else
        fn[len + i - 5] = '\0';

    i--;

 search:
    while(i < rc - 3)
      if(buf[i++] == '\r' && buf[i] == '\n'){
        i++; if(buf[i++] == '\r' && buf[i] == '\n')
          goto send;
      }

    if(rc < 4096) {
        rc += st_read(fd, buf + rc, 4096 - rc,-1);
        goto search;
    }

 send:
#ifdef STATIC
    rc = st_write(fd, &resp, resp_size, 60000000);
    if(rc != resp_size) { perror("st_write"); goto fail; }
#else
    ffd = open(fn, O_RDONLY,0);
    if(ffd < 0) {
        int err;
        char *message;
        if(errno == ENOENT) {
            err = 404;
            message = "File doesn't exist";
        } else if(errno == EACCES || errno == EPERM) {
            err = 403;
            message = "Forbidden";
        } else if(errno == EMFILE || errno == ENFILE) {
            err = 500;
            message = "Out of file descriptors";
        } else if(errno == ENOMEM) {
            err = 500;
            message = "Out of memory";
        } else {
            err = 500;
            message = "Unknown error";
        }
        n = snprintf(buf, 4096,
                     "HTTP/1.1 %d %s\r\n"
                     "Content-Type: text/html\r\n"
                     "Server: Trivial-st\r\n"
                     "Connection: close\r\n"
                     "\r\n"
                     "<html><body><p>Couldn't open %s: %s</body></html>\r\n",
                     err, message, fn, message);
        free(fn);
    } else {
        free(fn);
        n = snprintf(buf, 4096,
                     "HTTP/1.1 200 OK\r\n"
                     "Content-Type: text/html\r\n"
                     "Server: Trivial-st\r\n"
                     "Connection: close\r\n"
                     "\r\n");
        rc = read(ffd, buf + n, 4096 - n);
        if(rc >= 0)
            n += rc;
    }

    rc = st_write(fd, buf, n,-1);
    if(rc < 0) { perror("write"); if(ffd >= 0) close(ffd); goto fail; }

    if(ffd >= 0) {
        while(1) {
            n = read(ffd, buf, 4096);
            if(n <= 0) break;
            rc = st_write(fd, buf, 4096,-1);
            st_sleep(0);
        }
    }

    close(ffd);
#endif

 fail:
    st_netfd_close(fd);
    free(buf);
    st_thread_exit(NULL);
}