コード例 #1
0
ファイル: test4.c プロジェクト: 1018824313/sqlite
/*
** Usage:  thread_halt ID
**
** Cause a thread to shut itself down.  Wait for the shutdown to be
** completed.  If ID is "*" then stop all threads.
*/
static int tcl_thread_halt(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  int i;

  if( argc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " ID", 0);
    return TCL_ERROR;
  }
  if( argv[1][0]=='*' && argv[1][1]==0 ){
    for(i=0; i<N_THREAD; i++){
      if( threadset[i].busy ) stop_thread(&threadset[i]);
    }
  }else{
    i = parse_thread_id(interp, argv[1]);
    if( i<0 ) return TCL_ERROR;
    if( !threadset[i].busy ){
      Tcl_AppendResult(interp, "no such thread", 0);
      return TCL_ERROR;
    }
    stop_thread(&threadset[i]);
  }
  return TCL_OK;
}
コード例 #2
0
ファイル: ping.c プロジェクト: baryluk/collectd
static int ping_shutdown (void) /* {{{ */
{
  hostlist_t *hl;

  INFO ("ping plugin: Shutting down thread.");
  if (stop_thread () < 0)
    return (-1);

  hl = hostlist_head;
  while (hl != NULL)
  {
    hostlist_t *hl_next;

    hl_next = hl->next;

    sfree (hl->host);
    sfree (hl);

    hl = hl_next;
  }

  if (ping_data != NULL) {
    free (ping_data);
    ping_data = NULL;
  }

  return (0);
} /* }}} int ping_shutdown */
コード例 #3
0
ファイル: pigpiod_if2.c プロジェクト: Nicodus63/Raspberry
void pigpio_stop(int pi)
{
   if ((pi < 0) || (pi >= MAX_PI) || !gPiInUse[pi]) return;

   if (gPthNotify[pi])
   {
      stop_thread(gPthNotify[pi]);
      gPthNotify[pi] = 0;
   }

   if (gPigCommand[pi] >= 0)
   {
      if (gPigHandle[pi] >= 0)
      {
         pigpio_command(pi, PI_CMD_NC, gPigHandle[pi], 0, 1);
         gPigHandle[pi] = -1;
      }

      close(gPigCommand[pi]);
      gPigCommand[pi] = -1;
   }

   if (gPigNotify[pi] >= 0)
   {
      close(gPigNotify[pi]);
      gPigNotify[pi] = -1;
   }

   gPiInUse[pi] = 0;
}
コード例 #4
0
ファイル: pigpiod_if.c プロジェクト: flashspys/Quadcopter.js
void pigpio_stop(void)
{
   gPigStarted = 0;

   if (pthNotify)
   {
      stop_thread(pthNotify);
      pthNotify = 0;
   }

   if (gPigNotify >= 0)
   {
      if (gPigHandle >= 0)
      {
         pigpio_command(gPigNotify, PI_CMD_NC, gPigHandle, 0, 1);
         gPigHandle = -1;
      }

      close(gPigNotify);
      gPigNotify = -1;
   }

   if (gPigCommand >= 0)
   {
      if (gPigHandle >= 0)
      {
         pigpio_command(gPigCommand, PI_CMD_NC, gPigHandle, 0, 1);
         gPigHandle = -1;
      }

      close(gPigCommand);
      gPigCommand = -1;
   }
}
コード例 #5
0
ファイル: Client.cpp プロジェクト: goatattack/goatattack
Client::~Client() {
    /* stop music player */
    subsystem.stop_music_player();

    /* stop thread if running */
    if (running) {
        stop_thread();
    }

    /* cleanup server buffer */
    while (!server_events.empty()) {
        ServerEvent evt = server_events.front();
        server_events.pop();
        if (evt.data) {
            delete[] evt.data;
        }
    }

    /* cleanup */
    for (Players::iterator it = players.begin(); it != players.end(); it++) {
        delete *it;
    }

    /* close file if opened */
    if (fhnd) {
        fclose(fhnd);
    }

    /* delete partial downloaded file */
    if (current_download_filename.length()) {
        remove(current_download_filename.c_str());
    }
}
コード例 #6
0
ファイル: host.c プロジェクト: zzongaly/bbsettings
int main(int argc, const char *argv[]){
   printf("\n\n");

   // Listen to SIGINT signals (program termination)
   signal(SIGINT, signal_handler);

   // Tell linux not to use the user leds in the board.
   take_over_leds();

   // Load device tree overlay to enable PRU hardware.
   load_device_tree_overlay();

   // Load and run binary into pru0
   init_pru_program();

   open_sound_file();
   start_thread();

   /* while(!finish){ */
   sleep(5);
   /* } */
   prussdrv_pru_disable(PRU_NUM);
   prussdrv_exit ();
   stop_thread();

   close_sound_file();

   return 0;
}
コード例 #7
0
ファイル: chat_core.cpp プロジェクト: swatSTEAM/simple-chat
void ChatCore::tryconnect(const QString& nickname,
                                      const QString& ip, const QString& port)
{

    auto thread = new QThread(this);

    if (server != nullptr)
    {
        server->destroy_connection();
        delete server;
    }
    server = new Server(nickname.toStdString(), ip.toStdString(), port.toInt());
//    server->moveToThread(thread);
    connect(thread, SIGNAL(started()), server, SLOT(establish_connection()));

    connect(server, SIGNAL(connected()), this, SLOT(connection_established()));

    connect(server, SIGNAL(readyRead()), this, SLOT(message_received()));

    connect(server, SIGNAL(error(QAbstractSocket::SocketError)), this,
            SLOT(connection_failed(QAbstractSocket::SocketError)));

    connect(server, SIGNAL(stop_thread()), thread, SLOT(quit()));
    thread->start();
}
コード例 #8
0
ファイル: A3.cpp プロジェクト: DerNerger/CppProjects
bool test_A3_c() {
#ifdef A3_c
    stop_thread();
    return (!T.joinable());   
#else
    return false;
#endif
}
コード例 #9
0
ファイル: dig_thread_pool.c プロジェクト: zhiyuan2007/anyhost
void 
thread_pool_stop(thread_pool_t *tp)
{
    ASSERT(tp, "stop thread from empty thread pool");
	int i = 0;
	for (; i < tp->thread_count; ++i)
		stop_thread(tp->threads + i);
}
コード例 #10
0
void event_handler_manager::free_evh_resources()
{
	evh_logfunc("");

	// Flag thread to stop on next loop
	stop_thread();
	evh_logfunc("Thread stopped");
}
コード例 #11
0
PitchTracker::~PitchTracker() {
    stop_thread();
    fftwf_destroy_plan(m_fftwPlanFFT);
    fftwf_destroy_plan(m_fftwPlanIFFT);
    fftwf_free(m_fftwBufferTime);
    fftwf_free(m_fftwBufferFreq);
    delete[] m_input;
    delete[] m_buffer;
}
コード例 #12
0
ファイル: signal.cpp プロジェクト: Emily/rubinius
  void SignalHandler::shutdown(STATE) {
    for(std::list<int>::iterator i = watched_signals_.begin();
        i != watched_signals_.end();
        ++i)
    {
      signal(*i, SIG_DFL);
    }

    stop_thread(state);
  }
コード例 #13
0
ファイル: test7.c プロジェクト: 1018824313/sqlite
/*
** Usage:  client_halt ID
**
** Cause a client thread to shut itself down.  Wait for the shutdown to be
** completed.  If ID is "*" then stop all client threads.
*/
static int tcl_client_halt(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  int i;

  if( argc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " ID", 0);
    return TCL_ERROR;
  }
  if( argv[1][0]=='*' && argv[1][1]==0 ){
    for(i=0; i<N_THREAD; i++){
      if( threadset[i].busy ){
        stop_thread(&threadset[i]);
      }
    }
  }else{
    i = parse_client_id(interp, argv[1]);
    if( i<0 ) return TCL_ERROR;
    if( !threadset[i].busy ){
      Tcl_AppendResult(interp, "no such thread", 0);
      return TCL_ERROR;
    }
    stop_thread(&threadset[i]);
  }

  /* If no client threads are still running, also stop the server */
  for(i=0; i<N_THREAD && threadset[i].busy==0; i++){}
  if( i>=N_THREAD ){
    sqlite3_server_stop();
    while( 1 ){
      for(i=0; i<N_THREAD && threadset[i].nServer==0; i++);
      if( i==N_THREAD ) break;
      sched_yield();
    }
  }
  return TCL_OK;
}
コード例 #14
0
  void FinalizerHandler::finish(STATE, GCToken gct) {
    if(!self_) {
      if(process_list_ || !lists_->empty() || !live_list_->empty()) {
        rubinius::bug("FinalizerHandler worker thread dead during halt");
      } else {
        return;
      }
    }

    finishing_ = true;

    while(true) {
      {
        StopTheWorld stw(state, gct, 0);

        if(!process_list_) {
          if(live_list_->empty() && lists_->empty()) break;

          // Everything is garbage when halting so keep adding live objects to
          // finalize queue until done.
          if(!live_list_->empty()) {
            for(FinalizeObjects::iterator i = live_list_->begin();
                i != live_list_->end();
                ++i)
            {
              i->queued();
            }

            queue_objects();
          }

          first_process_item();
          if(!process_list_) break;
        }
      }

      worker_signal();

      {
        utilities::thread::Mutex::LockGuard lg(supervisor_lock_);

        state->vm()->set_call_frame(0);
        GCIndependent indy(state);
        if(process_list_) supervisor_wait();
      }
    }

    if(!lists_->empty() || !live_list_->empty() || process_list_ != NULL)
      rubinius::bug("FinalizerHandler exiting with pending finalizers");

    stop_thread(state);
  }
コード例 #15
0
thread_buffer_t::~thread_buffer_t()
{
    bool stopped=false;
    try {
        stopped=stop_thread();
    }catch( ... ) {
    }
    if( !stopped ) {
        try {
            stopped=abort_thread();
        }catch( ... ) {
        }
    }
    if( !stopped ) {
        std::terminate();
    }
}
コード例 #16
0
thread_buffer_t::~thread_buffer_t()
{
    bool stopped=false;
    try {
        stopped=stop_thread();
    }catch(...){
    }
    if( !stopped ) {
        // one more time, with attitude
        try {
            stopped=abort_thread();
        }catch(...){
        }
        if( !stopped ) {
            DWORD code=GetLastError();
            // otherwize, the thread will be left running loose stomping on freed memory.
            std::terminate();
        }
    }
}
コード例 #17
0
ファイル: host.c プロジェクト: zzongaly/bbsettings
int main(int argc, const char *argv[]){
	printf("\n\n");

	// Listen to SIGINT signals (program termination)
	signal(SIGINT, signal_handler);


	// Load device tree overlay to enable PRU hardware.
	load_device_tree_overlay();

	// Load and run binary into pru0
	init_pru_program();

	open_sound_file();

	/* sleep(1); */
	start_thread();

	while(!finish){}
	//sleep(500);

	prussdrv_pru_disable(PRU_NUM);
	prussdrv_exit ();
	stop_thread();

	close_sound_file();

	// Calculate sample rate
	/* int i; */
	/* unsigned long sum = 0; */
	/* for(i=0; i<times_count; i++){ */
	/*	 sum += times[i]; */
	/* } */
	/* float avg = (float)sum / (float)times_count; */
	/* printf("Freq: %f \n", 128.0*1000000.0/avg); */

	return 0;
}
コード例 #18
0
ファイル: finalize.cpp プロジェクト: Energy0124/rubinius
 void FinalizerHandler::before_exec(STATE) {
   stop_thread(state);
 }
コード例 #19
0
ファイル: linuxaio_queue.cpp プロジェクト: stxxl/stxxl
linuxaio_queue::~linuxaio_queue()
{
    stop_thread(post_thread, post_thread_state, num_waiting_requests);
    stop_thread(wait_thread, wait_thread_state, num_posted_requests);
    syscall(SYS_io_destroy, context);
}
コード例 #20
0
ファイル: chan_ss7.c プロジェクト: nicolastanski/chan_ss7
static void stop_mtp_thread(void)
{
    mtp_thread_signal_stop();
    stop_thread(&mtp_thread, &mtp_thread_running);
}
コード例 #21
0
ファイル: signal.cpp プロジェクト: Emily/rubinius
 void SignalHandler::before_exec(STATE) {
   stop_thread(state);
 }
コード例 #22
0
ProcessDialog::ProcessDialog (QWidget *parent) : QDialog (parent)
{
	setupUi (this);
	writeThread = new DThread;
	saver = new DSaver;
	aCurve = new DCurve;
	config = new DConfig;
	fprintf (stderr, "Objects initialized.\n");	
	zone_length = config->measure_num;
	zone_length_spin->setValue (zone_length);
	start_x = 0;
//	zone_length = 50;
//	start_x = 0;
//	end_x = zone_length;
	// ############## STANDART WIDGETS INITIALIZATION ############
	
	//zone_length_spin->setValue (static_cast<int>(aCurve->zone_length));
//	zone_length_spin->setValue (50);
//	QString scale_temp = QString::number (aCurve->maxX/zone_length, 'g', 4);
//	scale_value_label->setText (scale_temp); 
	saver->set_file_name ("default.dat");
	running = false;
	indicator_label->setText ("<font color=red> <b> NOT RUNNING </b> </font>");
	tabWidget->setTabText (0, "Diagram");
	tabWidget->setTabText (1, "Scheme");

	/*	Connections	*/
	connect (aCurve, SIGNAL ( pack_accepted () ), plot, SLOT ( replot() ));
	connect (aCurve, SIGNAL ( pack_accepted () ), this, SLOT (graph_next_frame()) );
	connect (writeThread, SIGNAL ( text_data (DPack *) ), this, SLOT ( process_pack (DPack *) ));
	connect (writeThread, SIGNAL ( chart_data (DPack *) ), aCurve, SLOT ( accept_data_pack (DPack *) ));
	connect (writeThread, SIGNAL ( save_data (DPack *) ), saver, SLOT (accept_data_pack (DPack *) ));
	connect (writeThread, SIGNAL ( done()), this, SLOT ( done()));
	connect (this, SIGNAL (rejected()), writeThread, SLOT (stop_thread()));
	// test routine
//	connect (this, SIGNAL (test_data_pack (DPack *)), this, SLOT ( process_pack (DPack *) ));
//	connect (this, SIGNAL (test_data_pack (DPack *)), aCurve, SLOT ( accept_data_pack (DPack *) ));
//	connect (this, SIGNAL (test_data_pack (DPack *)), saver, SLOT ( accept_data_pack (DPack *) ));
	/*	Properties	*/
	connect (channel1_box, SIGNAL (clicked()), this, SLOT (channel1_box_clicked()));
	connect (channel2_box, SIGNAL (clicked()), this, SLOT (channel2_box_clicked()));
	connect (channel3_box, SIGNAL (clicked()), this, SLOT (channel3_box_clicked()));
	connect (channel4_box, SIGNAL (clicked()), this, SLOT (channel4_box_clicked()));
	connect (channel5_box, SIGNAL (clicked()), this, SLOT (channel5_box_clicked()));
	connect (channel6_box, SIGNAL (clicked()), this, SLOT (channel6_box_clicked()));
	connect (zone_length_spin, SIGNAL (valueChanged (int)), this, SLOT (graph_update (int)));
	connect (this, SIGNAL (closed()), this, SLOT (renew()));
	
	fprintf (stderr, "Connections established,\n");
	// ###################  QwtPlot initialization ########################
       	for (int a = 0; a < 6; a ++)
	{
		QPen pen = QPen (config->colors[a]);
		pen.setWidth(2);
		aCurve->channel_curve[a]->setPen (pen);
        	aCurve->channel_curve[a]->attach (plot);
	}

        aCurve->setMaxX (config->measure_num); 
        aCurve->setStepX (config->chart_mod);
	fprintf (stderr, "ProcessDialog: stepx = config->chart_mod = %d.\n", config->chart_mod);

	QwtPlotGrid *grid = new QwtPlotGrid;
	
	grid->setMajPen (QPen (Qt::gray, 0, Qt::DotLine));
	grid->attach (plot);
	
	plot->setTitle ("Graphics diagram");
	plot->setCanvasBackground (Qt::white);
	plot->setAxisTitle (0,"Signal, V");
	plot->setAxisTitle (2,"Measure, num");
//	plot->setAxisScale (2, start_x, end_x, zone_length/10);		
	plot->setAxisScale (2, 0, config->measure_num, config->measure_num/10);
	//graph_update(zone_length);
	
	// ##################### TABLE INITIALIZATION #####################

	row = -1;
	display_table->setColumnCount (6);
	display_table->setRowCount(config->measure_num); 	
	for (int i = 0; i < 6; i++)
	{
		display_table->setColumnWidth (i, 40);
	}

	// ########### CHANNEL GROUP ######################

	QString temp = tr("<font color='%1'>%2</font>");
	QString text = "Ch1";
	channel1_label->setText (temp.arg (config->colors[0].name(), text));
	
	temp = tr("<font color='%1'>%2</font>");
	text = "Ch2";
	channel2_label->setText (temp.arg (config->colors[1].name(), text));
	
	temp = tr("<font color='%1'>%2</font>");
	text = "Ch3";
	channel3_label->setText (temp.arg (config->colors[2].name(), text));

	temp = tr("<font color='%1'>%2</font>");
	text = "Ch4";
	channel4_label->setText (temp.arg (config->colors[3].name(), text));

	temp = tr("<font color='%1'>%2</font>");
	text = "Ch5";
	channel5_label->setText (temp.arg (config->colors[4].name(), text));

	temp = tr("<font color='%1'>%2</font>");
	text = "Ch6";
	channel6_label->setText (temp.arg (config->colors[5].name(), text));

	fprintf (stderr, "ProcessDialog object created\n");
}
コード例 #23
0
ファイル: Client.cpp プロジェクト: goatattack/goatattack
void Client::idle() throw (Exception) {
    /* process net io */
    bool queue_empty = true;
    do {
        ServerEvent evt;
        {
            Scope<Mutex> lock(mtx);
            if (server_events.empty()) {
                break;
            }
            evt = server_events.front();
            server_events.pop();
            queue_empty = server_events.empty();
        }
        switch (evt.event) {
            case EventTypeStatus:
            {
                std::string msg(evt.data, evt.sz);
                subsystem << msg << std::endl;
                break;
            }

            case EventTypeAccessDenied:
            {
                stop_thread();
                exception_msg.assign(evt.data, evt.sz);
                throw_exception = true;
                break;
            }

            case EventTypeLogin:
            {
                sevt_login(evt);
                break;
            }

            case EventTypeLogout:
            {
                stop_thread();
                logged_in = false;
                conn = 0;
                exception_msg.assign(evt.data, evt.sz);
                throw_exception = true;
                break;
            }

            case EventTypeData:
                sevt_data(evt);
                break;
        }
        if (evt.data) {
            delete[] evt.data;
        }
    } while (!queue_empty && !throw_exception);

    /* have to throw an exception? */
    if (throw_exception) {
        throw ClientException(exception_msg);
    }

    /* interpolate movements */
    get_now(now);
    ns_t diff = diff_ns(last, now);

    last = now;

    if (tournament) {
        tournament->update_states(diff);
        if (conn) {
            tournament->set_ping_time(conn->ping_time);
            Tournament::StateResponses& responses = tournament->get_state_responses();
            size_t sz = responses.size();
            {
                Scope<Mutex> lock(mtx);
                for (size_t i = 0; i < sz; i++) {
                    StateResponse *resp = responses[i];
                    if (resp->action == GPCTextMessage) {
                        std::string msg(reinterpret_cast<const char *>(resp->data), resp->len);
                        add_text_msg(msg);
                    } else {
                        stacked_send_data(conn, factory.get_tournament_id(), resp->action, 0, resp->len, resp->data);
                    }
                }
                flush_stacked_send_data(conn, 0);
            }
        }
        tournament->delete_responses();

        /* send player position (unreliable) */
        updatecnt += diff;
        bool player_force = false;
        if (me && me->force_broadcast) {
            player_force = true;
            me->force_broadcast = false;
            me->state.client_server_state.flags |= PlayerClientServerFlagForceBroadcast;
        }
        if (updatecnt >= UpdatePeriod || force_send || player_force) {
            updatecnt = 0;
            if (conn && me && tournament->is_ready()) {
                GPlayerClientServerState state;
                state = me->state.client_server_state;
                state.to_net();
                {
                    Scope<Mutex> lock(mtx);
                    send_data(conn, factory.get_tournament_id(), GPSUpdatePlayerClientServerState, 0, GPlayerClientServerStateLen, &state);
                }
                me->state.client_server_state.flags &= ~PlayerClientServerFlagForceBroadcast;
            }
        }
    }

    /* interpolate messages */
    for (TextMessages::iterator it = text_messages.begin();
        it != text_messages.end(); it++)
    {
        TextMessage *cmsg = *it;
        cmsg->duration += (diff / 1000000.0f);
        if (cmsg->duration > text_message_duration) {
            cmsg->delete_me = true;
        }
    }
    text_messages.erase(std::remove_if(text_messages.begin(),
        text_messages.end(), erase_element<TextMessage>),
        text_messages.end());

    /* player in options or in chatbox? */
    if (me) {
        if (get_stack_count()) {
            me->state.client_server_state.flags |= PlayerClientServerFlagWriting;
        } else {
            me->state.client_server_state.flags &= ~PlayerClientServerFlagWriting;
        }
    }

    /* draw map */
    if (tournament) {
        tournament->draw();
    }

    /* draw messages */
    Font *font = resources.get_font("normal");
    int view_height = subsystem.get_view_height();
    int font_height = font->get_font_height();
    int y = view_height - font_height - 5;
    for (TextMessages::reverse_iterator it = text_messages.rbegin();
        it != text_messages.rend(); it++)
    {
        TextMessage *cmsg = *it;
        float alpha = 1.0f;
        if (cmsg->duration > text_message_fade_out_at) {
            alpha = static_cast<float>((text_message_duration - cmsg->duration) / (text_message_duration - text_message_fade_out_at));
        }

        subsystem.set_color(0.75f, 0.75f, 1.0f, alpha);
        subsystem.draw_text(font, 5, y, cmsg->text);
        alpha *= 0.9f;
        y -= font_height;
    }
    subsystem.reset_color();

    /* draw file transfer status */
    if (fhnd) {
        Font *big = resources.get_font("big");
        int percent = 100 - static_cast<int>(100.0f / static_cast<float>(total_xfer_sz) * remaining_xfer_sz);
        sprintf(buffer, "transferring %s (%d%%)", xfer_filename.c_str(), percent);
        int tw = big->get_text_width(buffer);
        subsystem.draw_text(big, subsystem.get_view_width() / 2 - tw / 2, view_height - 30, buffer);
    }
}
コード例 #24
0
ファイル: immix_marker.cpp プロジェクト: Emily/rubinius
 void ImmixMarker::shutdown(STATE) {
   stop_thread(state);
 }
コード例 #25
0
ファイル: immix_marker.cpp プロジェクト: Emily/rubinius
 void ImmixMarker::before_exec(STATE) {
   stop_thread(state);
 }
コード例 #26
0
ファイル: finalizer.cpp プロジェクト: nomadium/rubinius
    void FinalizerThread::stop(STATE) {
      state->shared().machine_threads()->unregister_thread(this);

      stop_thread(state);
    }
コード例 #27
0
ファイル: sgcomm_tx_test.c プロジェクト: sma-wideband/sdbe
int main(int argc, char **argv) {
	/* Slave threads */
	sgcomm_thread *st_rd; // Reader
	sgcomm_thread *st_tx; // Transmitter
	shared_buffer *sbtx; // shared buffer for read+transmit
	
	/* Reader message parameters */
	char *fmtstr = "/mnt/disks/%u/%u/data/%s";
	char *pattern_read = "input.vdif";
	char *host = "localhost";
	uint16_t port = 61234;
	int n_mod = 4;
	int mod_list[4] = { 1, 2, 3, 4};
	int n_disk = 8;
	int disk_list_read[8] = { 0, 1, 2, 3, 4, 5, 6, 7 };
	int disk_list_write[8] = { 1, 0, 2, 3, 4, 5, 6, 7 };
	
	/* Transmitter message parameters */
	if (argc > 1)
		pattern_read = argv[1];
	if (argc > 2)
		fmtstr = argv[2];
	if (argc > 3)
		host = argv[3];
	if (argc > 4)
		port = atoi(argv[4]);
	
	log_message(RL_NOTICE,"%s:Using input file '%s' matching pattern '%s'",__FUNCTION__,pattern_read,fmtstr);
	log_message(RL_NOTICE,"%s:Transmitting to %s:%u",__FUNCTION__,host,port);
	
	/* This thread */
	sgcomm_thread *st = &st_main;
	ctrl_state state;
	
	log_message(RL_DEBUG,"%s:Creating shared buffer",__FUNCTION__);
	
	/* Initialize shared data buffer */
	sbtx = create_shared_buffer(SHARED_BUFFER_SIZE_TX);
	if (sbtx == NULL)
		set_thread_state(st,CS_ERROR,"%s(%d):Cannot create shared buffer for read+transmit",__FUNCTION__,__LINE__);
	
	log_message(RL_DEBUG,"%s:Creating slave threads",__FUNCTION__);
	
	/* Create thread instances */
	st_rd = create_thread(TT_READER);
	if (st_rd == NULL)
		set_thread_state(st,CS_ERROR,"%s(%d):Cannot create reader thread",__FUNCTION__,__LINE__);
	st_tx = create_thread(TT_TRANSMITTER);
	if (st_tx == NULL)
		set_thread_state(st,CS_ERROR,"%s(%d):Cannot create transmitter thread",__FUNCTION__,__LINE__);
	
	log_message(RL_DEBUG,"%s:Initializing thread messages",__FUNCTION__);
	
	/* Initialize thread messages */
	init_reader_msg((reader_msg *)st_rd->type_msg, sbtx, pattern_read, fmtstr,
					mod_list, n_mod, disk_list_read, n_disk);
	init_transmitter_msg((transmitter_msg *)st_tx->type_msg, sbtx,
					host, port);
	
	/* Start transmitter thread */
	if (start_thread(st_tx) != 0)
		set_thread_state(st,CS_ERROR,"%s(%d):Cannot start transmitter thread",__FUNCTION__,__LINE__);
	/* Pause, then see if transmitter has error, if so, abort */
	usleep(MAIN_WAIT_PERIOD_US);
	if ((get_thread_state(st_tx,&state) == 0) && (state >= CS_STOP)) {
		set_thread_state(st,CS_ERROR,"%s(%d):Transmitter terminated prematurely, aborting start.",__FUNCTION__,__LINE__);
	} else {
		if (start_thread(st_rd) != 0)
			set_thread_state(st,CS_ERROR,"%s(%d):Cannot start reader thread",__FUNCTION__,__LINE__);
	}
	
	//~ log_message(RL_DEBUG,"%s:Entering main thread run loop",__FUNCTION__);
	
	if ((get_thread_state(st,&state) == 0) && !(state >= CS_STOP))
		set_thread_state(st,CS_RUN,"%s:Thread running",__FUNCTION__);
	while ((get_thread_state(st,&state) == 0) && !(state >= CS_STOP)) {
				
		// TODO: do something
		
		usleep(MAIN_WAIT_PERIOD_US);
		
		/* If any thread has a problem, stop all of them */
		if ( ((get_thread_state(st_rd,&state) == 0) && (state >= CS_ERROR)) ||
			 ((get_thread_state(st_tx,&state) == 0) && (state >= CS_ERROR)) ) {
			// TODO: Some cleanup?
			break;
		}
		
		/* If all threads are stopped, break */
		if ( ((get_thread_state(st_rd,&state) == 0) && (state >= CS_STOP)) &&
			 ((get_thread_state(st_tx,&state) == 0) && (state >= CS_STOP)) ) {
			log_message(RL_NOTICE,"%s:All threads stopped of their own volition",__FUNCTION__);
			break;
		}
		
		/* If reader thread is done, stop transmitter */
		if ( (get_thread_state(st_rd,&state) == 0) && (state >= CS_STOP) && 
			 (get_thread_state(st_tx,&state) == 0) && (state < CS_STOP)) {
			log_message(RL_NOTICE,"%s:Reader is done, stop transmitter",__FUNCTION__);
			/* Two wait periods should be enough - reader is the only
			 * other thread that can cause transmitter to wait on a 
			 * resource, and then it will only be a single wait. */
			usleep(MAIN_WAIT_PERIOD_US);
			usleep(MAIN_WAIT_PERIOD_US);
			if (stop_thread(st_tx) != 0)
				set_thread_state(st,CS_ERROR,"%s(%d):Cannot stop transmitter thread",__FUNCTION__,__LINE__);
		}
		
	}
	
	log_message(RL_DEBUG,"%s:Stopping slave threads",__FUNCTION__);
	
	/* Stop slave threads on tx side */
	if ( (get_thread_state(st_rd,&state) == 0) && (state < CS_STOP) && (state > CS_INIT) && stop_thread(st_rd) != 0)
		set_thread_state(st,CS_ERROR,"%s(%d):Cannot stop reader thread",__FUNCTION__,__LINE__);
	log_message(RL_DEBUGVVV,"%s:Reader thread stopped",__FUNCTION__);
	if ( (get_thread_state(st_tx,&state) == 0) && (state < CS_STOP) && (state > CS_INIT) && stop_thread(st_tx) != 0)
		set_thread_state(st,CS_ERROR,"%s(%d):Cannot stop transmitter thread",__FUNCTION__,__LINE__);
	log_message(RL_DEBUGVVV,"%s:Transmitter thread stopped",__FUNCTION__);
	
	log_message(RL_DEBUG,"%s:Destroying shared buffer",__FUNCTION__);
	
	/* Destroy shared data buffer */
	if (destroy_shared_buffer(&sbtx) != 0)
		set_thread_state(st,CS_ERROR,"%s(%d):Cannot destroy shared buffer for read+transmit",__FUNCTION__,__LINE__);
	
	log_message(RL_DEBUG,"%s:Destroying slave threads",__FUNCTION__);
	
	/* Destroy threads */
	destroy_thread(&st_rd);
	destroy_thread(&st_tx);
	
	log_message(RL_DEBUG,"%s:Everything is done, goodbye",__FUNCTION__);
	
	/* That's all folks! */
	// TODO: Report that we're done
	return EXIT_SUCCESS;
}
コード例 #28
0
ファイル: ping.c プロジェクト: baryluk/collectd
static int ping_read (void) /* {{{ */
{
  hostlist_t *hl;

  if (ping_thread_error != 0)
  {
    ERROR ("ping plugin: The ping thread had a problem. Restarting it.");

    stop_thread ();

    for (hl = hostlist_head; hl != NULL; hl = hl->next)
    {
      hl->pkg_sent = 0;
      hl->pkg_recv = 0;
      hl->latency_total = 0.0;
      hl->latency_squared = 0.0;
    }

    start_thread ();

    return (-1);
  } /* if (ping_thread_error != 0) */

  for (hl = hostlist_head; hl != NULL; hl = hl->next) /* {{{ */
  {
    uint32_t pkg_sent;
    uint32_t pkg_recv;
    double latency_total;
    double latency_squared;

    double latency_average;
    double latency_stddev;

    double droprate;

    /* Locking here works, because the structure of the linked list is only
     * changed during configure and shutdown. */
    pthread_mutex_lock (&ping_lock);

    pkg_sent = hl->pkg_sent;
    pkg_recv = hl->pkg_recv;
    latency_total = hl->latency_total;
    latency_squared = hl->latency_squared;

    hl->pkg_sent = 0;
    hl->pkg_recv = 0;
    hl->latency_total = 0.0;
    hl->latency_squared = 0.0;

    pthread_mutex_unlock (&ping_lock);

    /* This e. g. happens when starting up. */
    if (pkg_sent == 0)
    {
      DEBUG ("ping plugin: No packages for host %s have been sent.",
          hl->host);
      continue;
    }

    /* Calculate average. Beware of division by zero. */
    if (pkg_recv == 0)
      latency_average = NAN;
    else
      latency_average = latency_total / ((double) pkg_recv);

    /* Calculate standard deviation. Beware even more of division by zero. */
    if (pkg_recv == 0)
      latency_stddev = NAN;
    else if (pkg_recv == 1)
      latency_stddev = 0.0;
    else
      latency_stddev = sqrt (((((double) pkg_recv) * latency_squared)
          - (latency_total * latency_total))
          / ((double) (pkg_recv * (pkg_recv - 1))));

    /* Calculate drop rate. */
    droprate = ((double) (pkg_sent - pkg_recv)) / ((double) pkg_sent);

    submit (hl->host, "ping", latency_average);
    submit (hl->host, "ping_stddev", latency_stddev);
    submit (hl->host, "ping_droprate", droprate);
  } /* }}} for (hl = hostlist_head; hl != NULL; hl = hl->next) */

  return (0);
} /* }}} int ping_read */
コード例 #29
0
ファイル: metrics.cpp プロジェクト: Azzurrio/rubinius
 void Metrics::shutdown(STATE) {
   stop_thread(state);
 }
コード例 #30
0
ファイル: basicthread.cpp プロジェクト: kalinsha08/KSFeed
BasicThread::~BasicThread()
{
    stop_thread(true);
}