Exemplo n.º 1
0
void
thread_shutdown ()
{
    /* Make secondary threads exit wait() */
    global_doShutdown = TRUE;
    THREAD_BARRIER(global_barrierPtr, 0);

    long numThread = global_numThread;

    long i;
    for (i = 1; i < numThread; i++) {
        THREAD_JOIN(global_threads[i]);
    }

	global_numThread = 1;

    THREAD_BARRIER_FREE(global_barrierPtr);
    global_barrierPtr = NULL;

    free(global_threadIds);
    global_threadIds = NULL;

    free(global_threads);
    global_threads = NULL;

}
Exemplo n.º 2
0
int main(int argc, char ** argv) {
    shared_queue_t q;
    shared_queue_init(&q, N, sizeof(int));

    THREAD_T enqueue_thread;
    THREAD_T dequeue_thread;

    THREAD_INIT(enqueue_thread, enqueue_thread_main, &q);
    THREAD_INIT(dequeue_thread, dequeue_thread_main, &q);

    THREAD_JOIN(enqueue_thread);
    THREAD_JOIN(dequeue_thread);

    shared_queue_destroy(&q);
    return 0;
}
static void teardown(void) {
    running = false;
    THREAD_JOIN(server_thread);
    UA_Server_run_shutdown(server);
    UA_Server_delete(server);
    UA_ServerConfig_delete(config);
}
Exemplo n.º 4
0
static void teardown_register(void) {
    *running_register = false;
    THREAD_JOIN(server_thread_register);
    UA_Server_run_shutdown(server_register);
    UA_Boolean_delete(running_register);
    UA_Server_delete(server_register);
}
Exemplo n.º 5
0
TSS_RESULT
tcsd_threads_final()
{
	int rc;
	UINT32 i;

	MUTEX_LOCK(tm->lock);

	tm->shutdown = 1;

	MUTEX_UNLOCK(tm->lock);

	/* wait for all currently running threads to exit */
	for (i = 0; i < tm->max_threads; i++) {
		if (tm->thread_data[i].thread_id != THREAD_NULL) {
			if ((rc = THREAD_JOIN(*(tm->thread_data[i].thread_id), NULL))) {
				LogError("Thread join failed: error: %d", rc);
			}
		}
	}

	free(tm->thread_data);
	free(tm);

	return TSS_SUCCESS;
}
Exemplo n.º 6
0
static void teardown_lds(void) {
    *running_lds = false;
    THREAD_JOIN(server_thread_lds);
    UA_Server_run_shutdown(server_lds);
    UA_Boolean_delete(running_lds);
    UA_Server_delete(server_lds);
}
Exemplo n.º 7
0
/**
 * Finalizes processes structures for threads
 */
void process_deinit() {

  int iter;
  abort_processes = TRUE;
  
  for (iter = 0; iter < MAX_PROCESSES; iter++) {
   
    if (processes[iter].is_active == TRUE) {

      SOCKET_SHUTDOWN(&(processes[iter].proc_data->connection));
            
      // Waits for the thread to end and then destroys it
      THREAD_JOIN(processes[iter].work, TRUE);
      free(processes[iter].work);

      processes[iter].is_active = FALSE;

      SOCKET_CLOSE(&(processes[iter].proc_data->connection));

      free(processes[iter].proc_data);

    }
    
  }

}
Exemplo n.º 8
0
/*---------------------------------------------------------------------*/
BOOL ArchiveClose(H_ARCHIVE harchive)
{
    NODE *node;
    STREAM *stream;

    if (!ValidateHandle(harchive))
        return (FALSE);

    _archive[harchive].last_error = ARC_NO_ERROR;
    _archive_error = ARC_NO_ERROR;

    ArchiveLog(ARC_LOG_VERBOSE, "Close archive: %s", _archive[harchive].path);

    /* Close all open event files on archive... */
    if ((node = FirstNode(&_archive[harchive].streams))) {
        do {
            stream = (STREAM *) node->data;
            if (_archive[harchive].access == ARC_WRITE)
                CloseEventFileAndRename(harchive, stream);
            else
                CloseEventFile(stream);
        } while ((node = NextNode(node)) != NULL);
    }

    /* If open for write... */
    if (_archive[harchive].access == ARC_WRITE) {
        MUTEX_LOCK(&_archive[harchive].purge.mutex);
        if(_archive[harchive].purge.active ) {
            _archive[harchive].purge.stop = TRUE;
            MUTEX_UNLOCK(&_archive[harchive].purge.mutex);
            ArchiveLog(ARC_LOG_VERBOSE, "Stopping purge thread");
            SEM_POST(&_archive[harchive].purge.semaphore);
            THREAD_JOIN(&_archive[harchive].purge.thread_id);
        }
        else 
            MUTEX_UNLOCK(&_archive[harchive].purge.mutex);

        /* Mark as closed and write state to disk */
        _archive[harchive].state.write = FALSE;
        if (!WriteState(harchive))
            return (FALSE);
    }

    /* Close the state file */
    if (!FileClose(_archive[harchive].file)) {
        _archive[harchive].last_error = ARC_FILE_IO_ERROR;
        return (FALSE);
    }

    _n_archives--;

    /* Clear state */
    MUTEX_DESTROY(&_archive[harchive].mutex);
    DestroyList(&_archive[harchive].streams);
    DestroyPurge(&_archive[harchive].purge);

    InitArchive(harchive);

    return (TRUE);
}
Exemplo n.º 9
0
static void
thread_deferred_cb_skew(void *arg)
{
	struct basic_test_data *data = arg;
	struct timeval tv_timer = {4, 0};
	struct deferred_cb_queue *queue;
	time_t elapsed;
	int i;

	queue = event_base_get_deferred_cb_queue(data->base);
	tt_assert(queue);

	for (i = 0; i < QUEUE_THREAD_COUNT; ++i)
		deferred_data[i].queue = queue;

	timer_start = time(NULL);
	event_base_once(data->base, -1, EV_TIMEOUT, timer_callback, NULL,
			&tv_timer);
	event_base_once(data->base, -1, EV_TIMEOUT, start_threads_callback,
			NULL, NULL);
	event_base_dispatch(data->base);

	elapsed = timer_end - timer_start;
	TT_BLATHER(("callback count, %u", callback_count));
	TT_BLATHER(("elapsed time, %u", (unsigned)elapsed));
	/* XXX be more intelligent here.  just make sure skew is
	 * within 2 seconds for now. */
	tt_assert(elapsed >= 4 && elapsed <= 6);

end:
	for (i = 0; i < QUEUE_THREAD_COUNT; ++i)
		THREAD_JOIN(load_threads[i]);
}
Exemplo n.º 10
0
    ~Client()
    {
      destroy();
#ifdef CB_THREAD
      THREAD_JOIN(tid);
#endif
      callback.destroy();
    }
Exemplo n.º 11
0
 	void TEngine::StopRendering()
 	{
 		FRenderer->SetRendering(false);
 		THREAD_JOIN(FTRenderingThread, FThreadData, NULL);
 		FRenderer->DestroyRenderWindow();
 		ENGINE_INFO("Rendering stoped");
 		FRenderingRunning = false;
 	}
Exemplo n.º 12
0
 	void TEngine::PauseRendering()
 	{
 		FRenderer->SetRendering(false);
 		THREAD_JOIN(FTRenderingThread, FThreadData,NULL);
 		FRenderer->HideRenderWindow();
 		ENGINE_INFO("Rendering paused");

 	}
Exemplo n.º 13
0
// the destructor isn't thread safe wrt to the accessor functions
Trace::~Trace() {
  is_running_ = false;
  THREAD_JOIN(thread);
  // mutex lock isn't required now that the thread stopped
#ifdef _WIN32
  CloseHandle(fd_);
#else
  munmap((void*)backing_, backing_size_);
  close(fd_);
#endif
  //printf("dead\n");
}
Exemplo n.º 14
0
static void teardown(void) {
    removeSubscription();
    *running = false;
    THREAD_JOIN(server_thread);
    UA_Server_run_shutdown(server);
    UA_Boolean_delete(running);
    UA_Server_delete(server);
    UA_ServerConfig_delete(config);
    UA_Array_delete(selectClauses, nSelectClauses, &UA_TYPES[UA_TYPES_SIMPLEATTRIBUTEOPERAND]);

    UA_Client_disconnect(client);
    UA_Client_delete(client);
}
boolean extract_emergency_phr(char *phr_download_to_path, void (*backend_alert_msg_callback_handler_ptr)(char *alert_msg))
{
	// Setup a callback handler
	backend_alert_msg_callback_handler = backend_alert_msg_callback_handler_ptr;

	// Passing variable
	ptr_phr_download_to_path = &phr_download_to_path;

	init_main();

	// Create an emergency PHR extraction thread
	if(THREAD_CREATE(emergency_phr_extraction_thread_id, extract_emergency_phr_main, NULL) != 0)
		int_error("Creating a thread for \"extract_emergency_phr_main\" failed");

	while(1)
	{
		if(sem_wait(&wake_up_main_thread_mutex) != 0)
			int_error("Locking the mutex failed");

		// The emergency PHR extraction thread terminated
		if(emergency_phr_extraction_thread_terminated_flag)
			break;

		// Send an error message to frontend
		if(strlen(err_msg_to_frontend) > 0)
		{
			backend_alert_msg_handler_callback(err_msg_to_frontend);
			strcpy(err_msg_to_frontend, "");

			if(sem_post(&confirm_err_msg_sending_to_frontend_mutex) != 0)
				int_error("Unlocking the mutex failed");
		}
	}

	// Join the emergency PHR extraction thread
	if(THREAD_JOIN(emergency_phr_extraction_thread_id) != 0)
		int_error("Joining a thread \"extract_emergency_phr_main\" failed");

	// Send signal to confirm that the emergency PHR extraction thread has been terminated if the action was performed by a cancellation thread
	if(emergency_phr_extracting_cancellation_flag)
	{
		if(sem_post(&send_signal_to_confirm_cancellation_thread_mutex) != 0)
			int_error("Unlocking the mutex failed");

		if(sem_wait(&cancellation_thread_got_confirmation_mutex) != 0)
			int_error("Locking the mutex failed");
	}

	uninit_main();
	return transaction_success_status_flag;
}
Exemplo n.º 16
0
static inline void _fast_mtq_stop(fast_mtq f_mtq, int type)
{
	int i;
	void *ret;

	log_debug("Fast mtq. Stop all threads %d", type);

	f_mtq->shutdown = type;

	COND_BROADCAST(f_mtq->cond);

	for (i = 0; i < f_mtq->threads; i++) {
		THREAD_JOIN(f_mtq->threads_table[i], ret);
	}
}
void* findDongleThread(void* arg)
{
  static int args[MAX_COMPORT];
  int i;
  THREAD_T threads[MAX_COMPORT];
  for(i = 0; i < MAX_COMPORT; i++) {
    args[i] = i;
  }
  g_dongleSearchStatus = DONGLE_SEARCHING;
  /* Spawn worker threads to find the dongle on a com port */
  for(i = 0; i < MAX_COMPORT; i++) { 
    /* First, make sure there are less than MAX_THREADS running */
    MUTEX_LOCK(&g_giant_lock);
    while(
        (g_numThreads >= MAX_THREADS) &&
        (g_dongleSearchStatus == DONGLE_SEARCHING)
        ) 
    {
      COND_WAIT(&g_giant_cond, &g_giant_lock);
    }
    if(g_dongleSearchStatus != DONGLE_SEARCHING) {
      i++;
      MUTEX_UNLOCK(&g_giant_lock);
      break;
    }
    /* Spawn a thread */
    THREAD_CREATE(&threads[i], findDongleWorkerThread, &args[i]);
    g_numThreads++;
    MUTEX_UNLOCK(&g_giant_lock);
  }
  /* Join all threads */
  int j;
  for(j = 0; j < i; j++) {
    MUTEX_LOCK(&g_giant_lock);
    if(g_dongleSearchStatus != DONGLE_SEARCHING) {
      MUTEX_UNLOCK(&g_giant_lock);
      break;
    }
    MUTEX_UNLOCK(&g_giant_lock);
    THREAD_JOIN(threads[j]);
  }
  MUTEX_LOCK(&g_giant_lock);
  if(g_dongleSearchStatus == DONGLE_SEARCHING) {
    g_dongleSearchStatus = DONGLE_NOTFOUND;
  }
  MUTEX_UNLOCK(&g_giant_lock);
  return NULL;
}
void on_button_p1_next_clicked(GtkWidget* widget, gpointer data)
{
  /* First, disable the widget so it cannot be clicked again */
  gtk_widget_set_sensitive(widget, false);

  /* Make sure thread is joined */
  THREAD_JOIN(g_mainSearchThread);

  /* Reset state vars */
  g_dongleSearchStatus = DONGLE_SEARCHING;
  
  /* Start the main search thread */
  THREAD_CREATE(&g_mainSearchThread, findDongleThread, NULL);

  /* Start the search timeout */
  g_timeout_add(200, findDongleTimeout, NULL);
}
Exemplo n.º 19
0
static void
thread_deferred_cb_skew(void *arg)
{
	struct timeval tv_timer = {1, 0};
	struct event_base *base = NULL;
	struct event_config *cfg = NULL;
	struct timeval elapsed;
	int elapsed_usec;
	int i;

	cfg = event_config_new();
	tt_assert(cfg);
	event_config_set_max_dispatch_interval(cfg, NULL, 16, 0);

	base = event_base_new_with_config(cfg);
	tt_assert(base);

	for (i = 0; i < QUEUE_THREAD_COUNT; ++i)
		deferred_data[i].queue = base;

	evutil_gettimeofday(&timer_start, NULL);
	event_base_once(base, -1, EV_TIMEOUT, timer_callback, NULL,
			&tv_timer);
	event_base_once(base, -1, EV_TIMEOUT, start_threads_callback,
			NULL, NULL);
	event_base_dispatch(base);

	evutil_timersub(&timer_end, &timer_start, &elapsed);
	TT_BLATHER(("callback count, %u", callback_count));
	elapsed_usec =
	    (unsigned)(elapsed.tv_sec*1000000 + elapsed.tv_usec);
	TT_BLATHER(("elapsed time, %u usec", elapsed_usec));

	/* XXX be more intelligent here.  just make sure skew is
	 * within .4 seconds for now. */
	tt_assert(elapsed_usec >= 600000 && elapsed_usec <= 1400000);

end:
	for (i = 0; i < QUEUE_THREAD_COUNT; ++i)
		THREAD_JOIN(load_threads[i]);
	if (base)
		event_base_free(base);
	if (cfg)
		event_config_free(cfg);
}
Exemplo n.º 20
0
void openavbAcmpSMControllerStop()
{
	AVB_TRACE_ENTRY(AVB_TRACE_ACMP);

	if (bRunning) {
		openavbAcmpSMControllerSet_doTerminate(TRUE);

		THREAD_JOIN(openavbAcmpSmControllerThread, NULL);
	}

	SEM_ERR_T(err);
	SEM_DESTROY(openavbAcmpSMControllerSemaphore, err);
	SEM_LOG_ERR(err);

	openavbListDeleteList(openavbAcmpSMControllerVars.inflight);

	AVB_TRACE_EXIT(AVB_TRACE_ACMP);
}
Exemplo n.º 21
0
static int
k4w2_v4l2_stop(k4w2_t ctx)
{
    k4w2_v4l2 * v4l2 = (k4w2_v4l2 *)ctx;
    CHANNEL ch;

    if (0== v4l2->thread)
	return K4W2_ERROR;

    v4l2->shutdown = 1;
    THREAD_JOIN(v4l2->thread);
    v4l2->thread = 0;

    for (ch = ctx->begin; ch <= ctx->end; ++ch) {
	stop_camera(&v4l2->cam[ch]);
    }
    return K4W2_SUCCESS;
}
Exemplo n.º 22
0
void
httpd_stop(httpd_t *httpd)
{
	assert(httpd);

	MUTEX_LOCK(httpd->run_mutex);
	if (!httpd->running || httpd->joined) {
		MUTEX_UNLOCK(httpd->run_mutex);
		return;
	}
	httpd->running = 0;
	MUTEX_UNLOCK(httpd->run_mutex);

	THREAD_JOIN(httpd->thread);

	MUTEX_LOCK(httpd->run_mutex);
	httpd->joined = 1;
	MUTEX_UNLOCK(httpd->run_mutex);
}
static void teardown(void) {
    /* cleanup */
    UA_Client_disconnect(client);
    UA_Client_delete(client);
    running = false;
    THREAD_JOIN(server_thread);
    UA_NodeId_deleteMembers(&parentNodeId);
    UA_NodeId_deleteMembers(&parentReferenceNodeId);
    UA_NodeId_deleteMembers(&outNodeId);
    UA_Server_run_shutdown(server);
    UA_Server_delete(server);
#ifdef UA_ENABLE_HISTORIZING
    UA_free(gathering);
#endif
    if (!MUTEX_DESTROY(serverMutex)) {
        fprintf(stderr, "Server mutex was not destroyed correctly.\n");
        exit(1);
    }
}
Exemplo n.º 24
0
static void
thread_no_events(void *arg)
{
	THREAD_T thread;
	struct basic_test_data *data = arg;
	struct timeval starttime, endtime;
	int i;
	exit_base = data->base;

	memset(times,0,sizeof(times));
	for (i=0;i<5;++i) {
		event_assign(&time_events[i], data->base,
		    -1, 0, note_time_cb, &times[i]);
	}

	evutil_gettimeofday(&starttime, NULL);
	THREAD_START(thread, register_events_subthread, data->base);
	event_base_loop(data->base, EVLOOP_NO_EXIT_ON_EMPTY);
	evutil_gettimeofday(&endtime, NULL);
	tt_assert(event_base_got_break(data->base));
	THREAD_JOIN(thread);
	for (i=0; i<5; ++i) {
		struct timeval diff;
		double sec;
		evutil_timersub(&times[i], &starttime, &diff);
		sec = diff.tv_sec + diff.tv_usec/1.0e6;
		TT_BLATHER(("event %d at %.4f seconds", i, sec));
	}
	test_timeval_diff_eq(&starttime, &times[0], 100);
	test_timeval_diff_eq(&starttime, &times[1], 200);
	test_timeval_diff_eq(&starttime, &times[2], 400);
	test_timeval_diff_eq(&starttime, &times[3], 450);
	test_timeval_diff_eq(&starttime, &times[4], 500);
	test_timeval_diff_eq(&starttime, &endtime,  500);

end:
	;
}
Exemplo n.º 25
0
extern DLL_EXPORT bool openavbTLStop(tl_handle_t handle)
{
	AVB_TRACE_ENTRY(AVB_TRACE_TL);

	tl_state_t *pTLState = (tl_state_t *)handle;

	if (!pTLState) {
		AVB_LOG_ERROR("Invalid handle.");
		AVB_TRACE_EXIT(AVB_TRACE_TL);
		return FALSE;
	}

	if (pTLState->bRunning) {
		// don't set bStreaming to false here, that's needed to track
		// that the streaming thread is running, so we can shut it down.
		//pTLState->bStreaming = FALSE;
		pTLState->bRunning = FALSE;

		THREAD_JOIN(pTLState->TLThread, NULL);
	}

	AVB_TRACE_EXIT(AVB_TRACE_TL);
	return TRUE;
}
Exemplo n.º 26
0
int main(int argc, char ** argv) {
    if (argc != 2) {
        printf("usage: %s <number_of_philosopher>\n", argv[0]);
        return 0;
    }

    srand(time(NULL));
    int n = (int) strtol(argv[1], (char **)NULL, 10);

    MUTEX_T*  chopsticks = (MUTEX_T*) malloc(n * sizeof(MUTEX_T));
    THREAD_T* philosophers = (THREAD_T*) malloc(n * sizeof(THREAD_T));

    for (int i = 0; i < n; i++) {
        MUTEX_INIT(chopsticks[i]);
    }

    for (int i = 0; i < n; i++) {
        context_t* ctx = (context_t*) malloc(sizeof(context_t));
        ctx->id = i;
        ctx->left_chopstick = &chopsticks[i];
        ctx->right_chopstick = &chopsticks[(i+1) % n];

        THREAD_INIT(philosophers[i], print_hello, ctx);
    }

    for (int i = 0; i < n; i++) {
        THREAD_JOIN(philosophers[i]);
        THREAD_DESTROY(philosophers[i]);
    }

    for (int i = 0; i < n; i++) {
        MUTEX_DESTROY(chopsticks[i]);
    }

    return 0;
}
Exemplo n.º 27
0
static void
thread_conditions_simple(void *arg)
{
	struct timeval tv_signal, tv_timeout, tv_broadcast;
	struct alerted_record alerted[NUM_THREADS];
	THREAD_T threads[NUM_THREADS];
	struct cond_wait cond;
	int i;
	struct timeval launched_at;
	struct event wake_one;
	struct event wake_all;
	struct basic_test_data *data = arg;
	struct event_base *base = data->base;
	int n_timed_out=0, n_signal=0, n_broadcast=0;

	tv_signal.tv_sec = tv_timeout.tv_sec = tv_broadcast.tv_sec = 0;
	tv_signal.tv_usec = 30*1000;
	tv_timeout.tv_usec = 150*1000;
	tv_broadcast.tv_usec = 500*1000;

	EVTHREAD_ALLOC_LOCK(cond.lock, EVTHREAD_LOCKTYPE_RECURSIVE);
	EVTHREAD_ALLOC_COND(cond.cond);
	tt_assert(cond.lock);
	tt_assert(cond.cond);
	for (i = 0; i < NUM_THREADS; ++i) {
		memset(&alerted[i], 0, sizeof(struct alerted_record));
		alerted[i].cond = &cond;
	}

	/* Threads 5 and 6 will be allowed to time out */
	memcpy(&alerted[5].delay, &tv_timeout, sizeof(tv_timeout));
	memcpy(&alerted[6].delay, &tv_timeout, sizeof(tv_timeout));

	evtimer_assign(&wake_one, base, wake_one_timeout, &cond);
	evtimer_assign(&wake_all, base, wake_all_timeout, &cond);

	evutil_gettimeofday(&launched_at, NULL);

	/* Launch the threads... */
	for (i = 0; i < NUM_THREADS; ++i) {
		THREAD_START(threads[i], wait_for_condition, &alerted[i]);
	}

	/* Start the timers... */
	tt_int_op(event_add(&wake_one, &tv_signal), ==, 0);
	tt_int_op(event_add(&wake_all, &tv_broadcast), ==, 0);

	/* And run for a bit... */
	event_base_dispatch(base);

	/* And wait till the threads are done. */
	for (i = 0; i < NUM_THREADS; ++i)
		THREAD_JOIN(threads[i]);

	/* Now, let's see what happened. At least one of 5 or 6 should
	 * have timed out. */
	n_timed_out = alerted[5].timed_out + alerted[6].timed_out;
	tt_int_op(n_timed_out, >=, 1);
	tt_int_op(n_timed_out, <=, 2);

	for (i = 0; i < NUM_THREADS; ++i) {
		const struct timeval *target_delay;
		struct timeval target_time, actual_delay;
		if (alerted[i].timed_out) {
			TT_BLATHER(("%d looks like a timeout\n", i));
			target_delay = &tv_timeout;
			tt_assert(i == 5 || i == 6);
		} else if (evutil_timerisset(&alerted[i].alerted_at)) {
			long diff1,diff2;
			evutil_timersub(&alerted[i].alerted_at,
			    &launched_at, &actual_delay);
			diff1 = timeval_msec_diff(&actual_delay,
			    &tv_signal);
			diff2 = timeval_msec_diff(&actual_delay,
			    &tv_broadcast);
			if (abs(diff1) < abs(diff2)) {
				TT_BLATHER(("%d looks like a signal\n", i));
				target_delay = &tv_signal;
				++n_signal;
			} else {
				TT_BLATHER(("%d looks like a broadcast\n", i));
				target_delay = &tv_broadcast;
				++n_broadcast;
			}
		} else {
			TT_FAIL(("Thread %d never got woken", i));
			continue;
		}
		evutil_timeradd(target_delay, &launched_at, &target_time);
		test_timeval_diff_leq(&target_time, &alerted[i].alerted_at,
		    0, 50);
	}
	tt_int_op(n_broadcast + n_signal + n_timed_out, ==, NUM_THREADS);
	tt_int_op(n_signal, ==, 1);

end:
	;
}
boolean download_emergency_phr(char *target_emergency_server_ip_addr, char *phr_owner_name, char *phr_owner_authority_name, unsigned int phr_id, char *phr_description, 
	boolean is_restricted_level_phr_flag, void (*backend_alert_msg_callback_handler_ptr)(char *alert_msg), void (*backend_fatal_alert_msg_callback_handler_ptr)(
	char *alert_msg), void (*set_emergency_phr_ems_side_processing_success_state_callback_handler_ptr)(), 
	void (*update_emergency_phr_received_progression_callback_handler_ptr)(unsigned int percent))
{
	// Setup allback handlers
	backend_alert_msg_callback_handler                                   = backend_alert_msg_callback_handler_ptr;
	backend_fatal_alert_msg_callback_handler                             = backend_fatal_alert_msg_callback_handler_ptr;
	set_emergency_phr_ems_side_processing_success_state_callback_handler = set_emergency_phr_ems_side_processing_success_state_callback_handler_ptr;
	update_emergency_phr_received_progression_callback_handler           = update_emergency_phr_received_progression_callback_handler_ptr;

	// Passing variable
	ptr_target_emergency_server_ip_addr = &target_emergency_server_ip_addr;

	char    buffer[BUFFER_LENGTH + 1];
	char    phr_id_str_tmp[INT_TO_STR_DIGITS_LENGTH + 1];
	boolean emergency_phr_downloading_status;

	init_main();
	set_waiting_server_processing_flag(false);
	set_emergency_phr_downloading_flag(false);

	// Connect to the emergency server
	if(!connect_to_emergency_phr_downloading_service(phr_owner_authority_name, &ssl_conn))
		goto ERROR;

	// Send request type information
	write_token_into_buffer("request_type", (is_restricted_level_phr_flag) ? RESTRICTED_LEVEL_PHR_ACCESSING : SECURE_LEVEL_PHR_ACCESSING, true, buffer);

	if(!SSL_send_buffer(ssl_conn, buffer, strlen(buffer)))
	{
		backend_alert_msg_handler_callback("Sending request type information failed");
		goto ERROR;
	}

	sprintf(phr_id_str_tmp, "%u", phr_id);

	// Send the requested emergency PHR information
	write_token_into_buffer("desired_phr_owner_name", phr_owner_name, true, buffer);
	write_token_into_buffer("phr_id", phr_id_str_tmp, false, buffer);
	write_token_into_buffer("phr_description", phr_description, false, buffer);

	if(!SSL_send_buffer(ssl_conn, buffer, strlen(buffer)))
	{
		backend_alert_msg_handler_callback("Sending the requested emergency PHR information failed");
		goto ERROR;
	}

	// Create a waiting server processing thread
	if(THREAD_CREATE(waiting_server_processing_thread_id, wait_server_processing_main, NULL) != 0)
		int_error("Creating a thread for \"wait_server_processing_main\" failed");

	set_waiting_server_processing_flag(true);

	while(1)
	{
		if(sem_wait(&wake_up_main_thread_mutex) != 0)
			int_error("Locking the mutex failed");

		// The waiting server processing thread terminated
		if(waiting_server_processing_thread_terminated_flag)
			break;

		// Send an error message to frontend
		if(strlen(err_msg_to_frontend) > 0)
		{
			backend_alert_msg_handler_callback(err_msg_to_frontend);
			strcpy(err_msg_to_frontend, "");

			if(sem_post(&confirm_err_msg_sending_to_frontend_mutex) != 0)
				int_error("Unlocking the mutex failed");
		}
	}

	set_waiting_server_processing_flag(false);

	// Join the waiting server processing thread
	if(THREAD_JOIN(waiting_server_processing_thread_id) != 0)
		int_error("Joining a thread \"wait_server_processing_main\" failed");

	// Send signal to confirm that the waiting server processing thread has been terminated if the action was performed by a cancellation thread
	if(emergency_phr_downloading_cancellation_flag)
	{
		if(sem_post(&send_signal_to_confirm_cancellation_thread_mutex) != 0)
			int_error("Unlocking the mutex failed");

		if(sem_wait(&cancellation_thread_got_confirmation_mutex) != 0)
			int_error("Locking the mutex failed");

		goto OPERATION_HAS_BEEN_CANCELLED;
	}

	if(!waiting_server_processing_success_status_flag)
	{
		goto ERROR;
	}

	set_emergency_phr_ems_side_processing_success_state_handler_callback();
	set_emergency_phr_downloading_flag(true);

	// Download the emergency PHR
	emergency_phr_downloading_status = SSL_recv_phr_file(ssl_conn, UNARCHIVED_EMERGENCY_PHR_TARGET_FILE_PATH);

	if(!emergency_phr_downloading_status && !emergency_phr_downloading_cancellation_flag)
	{
		char err_msg[ERR_MSG_LENGTH + 1];

		sprintf(err_msg, "Receiving the %s-level PHR file failed", (is_restricted_level_phr_flag) ? "restricted" : "secure");
		backend_alert_msg_callback_handler(err_msg);
		goto ERROR;
	}

	set_emergency_phr_downloading_flag(false);

	// Send signal to confirm that the download operation has been cancelled if the action was performed by a cancellation thread
	if(emergency_phr_downloading_cancellation_flag)
	{
		if(sem_post(&send_signal_to_confirm_cancellation_thread_mutex) != 0)
			int_error("Unlocking the mutex failed");

		if(sem_wait(&cancellation_thread_got_confirmation_mutex) != 0)
			int_error("Locking the mutex failed");

		goto OPERATION_HAS_BEEN_CANCELLED;
	}

	SSL_cleanup(ssl_conn);
	ssl_conn = NULL;

	uninit_main();
	return true;

ERROR:
OPERATION_HAS_BEEN_CANCELLED:

	set_emergency_phr_downloading_flag(false);
	set_waiting_server_processing_flag(false);

	unlink(UNARCHIVED_EMERGENCY_PHR_TARGET_FILE_PATH);

	if(ssl_conn)
	{
		SSL_cleanup(ssl_conn);
		ssl_conn = NULL;
	}

	uninit_main();
	return false;
}
Exemplo n.º 29
0
int main(int argc, char *argv[])
{
    int ch;
    extern char *optarg;
    int i, j, r;
    thread_t threads[MAX_TPP];

    /* init MP */
    MP_INIT(argc,argv);
    MP_PROCS(&size);
    MP_MYID(&rank);

    while ((ch = getopt(argc, argv, "t:s:i:d:h")) != -1) {
        switch(ch) {
            case 't': /* # of threads */
                tpp = atoi(optarg);
                if (tpp < 1 || tpp > MAX_TPP) {
                    PRINTF0("\"%s\" is improper value for -t, should be a "
                            "number between 1 and %d(MAX_TPP)\n",
                            optarg, MAX_TPP);
                    usage();
                }
                break;
            case 'i': /* # of iterations */
                iters = atoi(optarg);
                if (iters < 1) {
                    PRINTF0("\"%s\" is improper value for -t, should be a "
                            "number equal or larger than 1\n", optarg);
                    usage();
                }
                break;
            case 's': /* # of elements in the array */
                asize = atoi(optarg);
                if (iters < 1) {
                    PRINTF0("\"%s\" is improper value for -s, should be a "
                            "number equal or larger than 1\n", optarg);
                    usage();
                }
                break;
            case 'd': delay = atoi(optarg); break; /* delay before start */
            case 'h': usage(); break; /* print usage info */
        }
    }
#ifdef NOTHREADS
    tpp = 1;
    PRINTF0("Warning: NOTHREADS debug symbol is set -- running w/o threads\n");
#endif
    th_size = size * tpp;
    PRINTF0("\nTest of multi-threaded capabilities:\n"
            "%d threads per process (%d threads total),\n"
            "%d array elements of size %d,\n"
            "%d iteration(s)\n\n", tpp, th_size, asize, sizeof(atype_t), iters);
    if (delay) {
        printf("%d: %d\n", rank, getpid());
        fflush(stdout);
        sleep(delay);
        MP_BARRIER();
    }
    TH_INIT(size,tpp);
    for (i = 0; i < tpp; i++) th_rank[i] = rank * tpp + i;

#if defined(DEBUG) && defined(LOG2FILE)
    for (i = 0; i < tpp; i++) {
        fname[10] = '0' + th_rank[i] / 100;
        fname[11] = '0' + th_rank[i] % 100 / 10;
        fname[12] = '0' + th_rank[i] % 10;
        dbg[i] = fopen(fname, "w");
    }
#endif
    for (i = 0; i < tpp; i++)
        prndbg(i, "proc %d, thread %d(%d):\n", rank, i, th_rank[i]);

    /* init ARMCI */
    ARMCI_Init();

    /* set global seed (to ensure same random sequence across procs) */
    time_seed = (unsigned)time(NULL);
    armci_msg_brdcst(&time_seed, sizeof(time_seed), 0);
    srand(time_seed); rand();
    prndbg(0, "seed = %u\n", time_seed);
    /* random pairs */
    pairs = calloc(th_size, sizeof(int));
    for (i = 0; i < th_size; i++) pairs[i] = -1;
    for (i = 0; i < th_size; i++) {
        if (pairs[i] != -1) continue;
        r = RND(0, th_size);
        while (i == r || pairs[r] != -1 ) r = RND(0, th_size);
        pairs[i] = r; pairs[r] = i;
    }
    for (i = 0, cbufl = 0; i < th_size; i++)
        cbufl += sprintf(cbuf + cbufl, " %d->%d|%d->%d",
                         i, pairs[i], pairs[i], pairs[pairs[i]]);
    prndbg(0, "random pairs:%s\n", cbuf);
    /* random targets */
    rnd_tgts = calloc(th_size, sizeof(int));
    for (i = 0, cbufl = 0; i < th_size; i++) {
        rnd_tgts[i] = RND(0, th_size);
        if (rnd_tgts[i] == i) { i--; continue; }
        cbufl += sprintf(cbuf + cbufl, " %d", rnd_tgts[i]);
    }
    prndbg(0, "random targets:%s\n", cbuf);
    /* random one */
    rnd_one = RND(0, th_size);
    prndbg(0, "random one = %d\n", rnd_one);

    assert(ptrs1 = calloc(th_size, sizeof(void *)));
    assert(ptrs2 = calloc(th_size, sizeof(void *)));
#ifdef NOTHREADS
    thread_main((void *)(long)0);
#else
    for (i = 0; i < tpp; i++) THREAD_CREATE(threads + i, thread_main, (void *)(long)i);
    for (i = 0; i < tpp; i++) THREAD_JOIN(threads[i], NULL);
#endif

    MP_BARRIER();
    PRINTF0("Tests Completed\n");

    /* clean up */
#if defined(DEBUG) && defined(LOG2FILE)
    for (i = 0; i < tpp; i++) fclose(dbg[i]);
#endif
    ARMCI_Finalize();
    TH_FINALIZE();
    MP_FINALIZE();

	return 0;
}
Exemplo n.º 30
0
int main(int argc, char *argv[])
{
	THREAD_TYPE user_authentication_thread_id;
	THREAD_TYPE pub_key_serving_thread_id;
	THREAD_TYPE user_info_management_thread_id;
	THREAD_TYPE server_info_management_thread_id;
	THREAD_TYPE user_list_loading_thread_id;
	THREAD_TYPE phr_authority_list_loading_thread_id;
	THREAD_TYPE user_management_thread_id;
	THREAD_TYPE phr_authority_management_thread_id;
	THREAD_TYPE user_passwd_resetting_thread_id;

	init_server();

	// Create threads
	if(THREAD_CREATE(user_authentication_thread_id, user_authentication_main, NULL) != 0)
	{
		uninit_server();
		int_error("Creating a thread for \"user_authentication_main\" failed");
		return 1;
	}

	if(THREAD_CREATE(pub_key_serving_thread_id, pub_key_serving_main, NULL) != 0)
	{
		uninit_server();
		int_error("Creating a thread for \"pub_key_serving_main\" failed");
		return 1;
	}

	if(THREAD_CREATE(user_info_management_thread_id, user_info_management_main, NULL) != 0)
	{
		uninit_server();
		int_error("Creating a thread for \"user_info_management_main\" failed");
		return 1;
	}

	if(THREAD_CREATE(server_info_management_thread_id, server_info_management_main, NULL) != 0)
	{
		uninit_server();
		int_error("Creating a thread for \"server_info_management_main\" failed");
		return 1;
	}

	if(THREAD_CREATE(user_list_loading_thread_id, user_list_loading_main, NULL) != 0)
	{
		uninit_server();
		int_error("Creating a thread for \"user_list_loading_main\" failed");
		return 1;
	}

	if(THREAD_CREATE(phr_authority_list_loading_thread_id, phr_authority_list_loading_main, NULL) != 0)
	{
		uninit_server();
		int_error("Creating a thread for \"phr_authority_list_loading_main\" failed");
		return 1;
	}

	if(THREAD_CREATE(user_management_thread_id, user_management_main, NULL) != 0)
	{
		uninit_server();
		int_error("Creating a thread for \"user_management_main\" failed");
		return 1;
	}

	if(THREAD_CREATE(phr_authority_management_thread_id, phr_authority_management_main, NULL) != 0)
	{
		uninit_server();
		int_error("Creating a thread for \"phr_authority_management_main\" failed");
		return 1;
	}

	if(THREAD_CREATE(user_passwd_resetting_thread_id, user_passwd_resetting_main, NULL) != 0)
	{
		uninit_server();
		int_error("Creating a thread for \"user_passwd_resetting_main\" failed");
		return 1;
	}

	printf("Emergency unit: %s.Emergency_Staff_Authority started...\n", GLOBAL_authority_name);

	// Join threads
	if(THREAD_JOIN(user_authentication_thread_id) != 0)
	{
		uninit_server();
		int_error("Joining a thread \"user_authentication_main\" failed");
		return 1;
	}

	if(THREAD_JOIN(pub_key_serving_thread_id) != 0)
	{
		uninit_server();
		int_error("Joining a thread \"pub_key_serving_main\" failed");
		return 1;
	}

	if(THREAD_JOIN(user_info_management_thread_id) != 0)
	{
		uninit_server();
		int_error("Joining a thread \"user_info_management_main\" failed");
		return 1;
	}

	if(THREAD_JOIN(server_info_management_thread_id) != 0)
	{
		uninit_server();
		int_error("Joining a thread \"server_info_management_main\" failed");
		return 1;
	}

	if(THREAD_JOIN(user_list_loading_thread_id) != 0)
	{
		uninit_server();
		int_error("Joining a thread \"user_list_loading_main\" failed");
		return 1;
	}

	if(THREAD_JOIN(phr_authority_list_loading_thread_id) != 0)
	{
		uninit_server();
		int_error("Joining a thread \"phr_authority_list_loading_main\" failed");
		return 1;
	}

	if(THREAD_JOIN(user_management_thread_id) != 0)
	{
		uninit_server();
		int_error("Joining a thread \"user_management_main\" failed");
		return 1;
	}

	if(THREAD_JOIN(phr_authority_management_thread_id) != 0)
	{
		uninit_server();
		int_error("Joining a thread \"phr_authority_management_main\" failed");
		return 1;
	}

	if(THREAD_JOIN(user_passwd_resetting_thread_id) != 0)
	{
		uninit_server();
		int_error("Joining a thread \"user_passwd_resetting_main\" failed");
		return 1;
	}

	uninit_server();
    	return 0;
}