コード例 #1
0
ファイル: main.c プロジェクト: DanielTillett/foundation_lib
DECLARE_TEST( ringbufferstream, threadedio )
{
	ringbufferstream_test_t test = {0};
	uint32_t* srcbuffer;
	unsigned int si;
	unsigned int loop, loops;
	real elapsed, throughput;
	unsigned int mbytes;

#if FOUNDATION_PLATFORM_ANDROID || FOUNDATION_PLATFORM_IOS
	mbytes = 16;
	loops = 32;
#else
	mbytes = 256;
	loops = 16;
#endif


	test.buffer_size = mbytes * 1024 * 1024;

	srcbuffer = memory_allocate( test.buffer_size, 0, MEMORY_PERSISTENT );
	
	test.source_buffer = (void*)srcbuffer;
	test.dest_buffer   = memory_allocate_zero( test.buffer_size, 0, MEMORY_PERSISTENT );

	for( si = 0; si < ( test.buffer_size / 4 ); ++si )
		srcbuffer[si] = random32();

	elapsed = 0;
	for( loop = 0; loop < loops; ++loop )
	{
		test.stream = ringbuffer_stream_allocate( 23477, test.buffer_size );

		test.read_thread = thread_create( read_thread, "reader", THREAD_PRIORITY_NORMAL, 0 );
		test.write_thread = thread_create( write_thread, "writer", THREAD_PRIORITY_NORMAL, 0 );

		thread_start( test.read_thread, &test );
		thread_start( test.write_thread, &test );
		thread_sleep( 100 );

		while( thread_is_running( test.read_thread ) || thread_is_running( test.write_thread ) )
			thread_sleep( 10 );

		thread_destroy( test.read_thread );
		thread_destroy( test.write_thread );

		for( si = 0; si < test.buffer_size; ++si )
			EXPECT_EQ( test.source_buffer[si], test.dest_buffer[si] );

		stream_deallocate( test.stream );

		elapsed += time_ticks_to_seconds( time_diff( test.start_time, test.end_time ) );
	}
	throughput = (real)( (float64_t)( mbytes * loops ) / (float64_t)elapsed );
	log_infof( HASH_TEST, "Ringbuffer throughput: %d MiB in %.2f sec -> %.2f MiB/sec", ( loops * mbytes ), (float32_t)elapsed, (float32_t)throughput );

	elapsed = 0;
	for( loop = 0; loop < loops; ++loop )
	{
		test.start_time = time_current();
		memcpy( test.dest_buffer, test.source_buffer, test.buffer_size );
		test.end_time = time_current();

		for( si = 0; si < test.buffer_size; ++si )
			EXPECT_EQ( test.source_buffer[si], test.dest_buffer[si] );

		elapsed += time_ticks_to_seconds( time_diff( test.start_time, test.end_time ) );
	}
	throughput = (real)( (float64_t)( mbytes * loops ) / (float64_t)elapsed );
	log_infof( HASH_TEST, "Memcpy     throughput: %d MiB in %.2f sec -> %.2f MiB/sec", ( loops * mbytes ), (float32_t)elapsed, (float32_t)throughput );

	memory_deallocate( test.source_buffer );
	memory_deallocate( test.dest_buffer );
	
	return 0;
}
コード例 #2
0
ファイル: labyrinth.c プロジェクト: chrisseaton/stamp
/* =============================================================================
 * main
 * =============================================================================
 */
MAIN(argc, argv)
{
    GOTO_REAL();

    /*
     * Initialization
     */
    parseArgs(argc, (char** const)argv);
    long numThread = global_params[PARAM_THREAD];
    SIM_GET_NUM_CPU(numThread);
    TM_STARTUP(numThread);
    P_MEMORY_STARTUP(numThread);
    thread_startup(numThread);
    maze_t* mazePtr = maze_alloc();
    assert(mazePtr);
    long numPathToRoute = maze_read(mazePtr, global_inputFile);
    router_t* routerPtr = router_alloc(global_params[PARAM_XCOST],
                                       global_params[PARAM_YCOST],
                                       global_params[PARAM_ZCOST],
                                       global_params[PARAM_BENDCOST]);
    assert(routerPtr);
    list_t* pathVectorListPtr = list_alloc(NULL);
    assert(pathVectorListPtr);

    /*
     * Run transactions
     */
    router_solve_arg_t routerArg = {routerPtr, mazePtr, pathVectorListPtr};
    TIMER_T startTime;
    TIMER_READ(startTime);
    GOTO_SIM();
#ifdef OTM
#pragma omp parallel
    {
        router_solve((void *)&routerArg);
    }
#else
    thread_start(router_solve, (void*)&routerArg);
#endif
    GOTO_REAL();
    TIMER_T stopTime;
    TIMER_READ(stopTime);

    long numPathRouted = 0;
    list_iter_t it;
    list_iter_reset(&it, pathVectorListPtr);
    while (list_iter_hasNext(&it, pathVectorListPtr)) {
        vector_t* pathVectorPtr = (vector_t*)list_iter_next(&it, pathVectorListPtr);
        numPathRouted += vector_getSize(pathVectorPtr);
    }
    printf("Paths routed    = %li\n", numPathRouted);
    printf("Elapsed time    = %f seconds\n", TIMER_DIFF_SECONDS(startTime, stopTime));

    /*
     * Check solution and clean up
     */
    assert(numPathRouted <= numPathToRoute);
    bool_t status = maze_checkPaths(mazePtr, pathVectorListPtr, global_doPrint);
    assert(status == TRUE);
    puts("Verification passed.");
    maze_free(mazePtr);
    router_free(routerPtr);

    TM_SHUTDOWN();
    P_MEMORY_SHUTDOWN();

    GOTO_SIM();

    thread_shutdown();


    MAIN_RETURN(0);
}
コード例 #3
0
ファイル: main.cpp プロジェクト: katakk/iperf
/* -------------------------------------------------------------------
 * main()
 *      Entry point into Iperf
 *
 * sets up signal handlers
 * initialize global locks and conditions
 * parses settings from environment and command line
 * starts up server or client thread
 * waits for all threads to complete
 * ------------------------------------------------------------------- */
int main( int argc, char **argv ) {
#ifdef WIN32
    // Start winsock
    WSADATA wsaData;
    int rc;
#endif

    // Set SIGTERM and SIGINT to call our user interrupt function
    my_signal( SIGTERM, Sig_Interupt );
    my_signal( SIGINT,  Sig_Interupt );
#ifndef WIN32 // SIGALRM=14, _NSIG=3...
    my_signal( SIGALRM,  Sig_Interupt );
#endif

#ifndef WIN32
	// Ignore broken pipes
    signal(SIGPIPE,SIG_IGN);
#endif

#ifdef WIN32 
    // Start winsock
    rc = WSAStartup( 0x202, &wsaData );
    WARN_errno( rc == SOCKET_ERROR, "WSAStartup" );
    if (rc == SOCKET_ERROR)
        return 0;

    // Tell windows we want to handle our own signals
    SetConsoleCtrlHandler( sig_dispatcher, true );
#endif

    // Initialize global mutexes and conditions
    Condition_Initialize ( &ReportCond );
    Condition_Initialize ( &ReportDoneCond );
    Mutex_Initialize( &groupCond );
    Mutex_Initialize( &clients_mutex );

    // Initialize the thread subsystem
    thread_init( );

    // Initialize the interrupt handling thread to 0
    sThread = thread_zeroid();

    // perform any cleanup when quitting Iperf
    atexit( cleanup );

    // Allocate the "global" settings
    thread_Settings* ext_gSettings = new thread_Settings;

    // Initialize settings to defaults
    Settings_Initialize( ext_gSettings );
    // read settings from environment variables
    Settings_ParseEnvironment( ext_gSettings );
    // read settings from command-line parameters
    Settings_ParseCommandLine( argc, argv, ext_gSettings );

    // Check for either having specified client or server
    if ( ext_gSettings->mThreadMode == kMode_Client
         || ext_gSettings->mThreadMode == kMode_Listener ) {
#ifdef WIN32
        // Start the server as a daemon
        // Daemon mode for non-windows in handled
        // in the listener_spawn function
        if ( isDaemon( ext_gSettings ) ) {
            CmdInstallService(argc, argv);
            return 0;
        }

        // Remove the Windows service if requested
        if ( isRemoveService( ext_gSettings ) ) {
            // remove the service
            if ( CmdRemoveService() ) {
                fprintf(stderr, "IPerf Service is removed.\n");

                return 0;
            }
        }
#endif
        // initialize client(s)
        if ( ext_gSettings->mThreadMode == kMode_Client ) {
            client_init( ext_gSettings );
        }

#ifdef HAVE_THREAD
        // start up the reporter and client(s) or listener
        {
            thread_Settings *into = NULL;
            // Create the settings structure for the reporter thread
            Settings_Copy( ext_gSettings, &into );
            into->mThreadMode = kMode_Reporter;

            // Have the reporter launch the client or listener
            into->runNow = ext_gSettings;

            // Start all the threads that are ready to go
            thread_start( into );
        }
#else
        // No need to make a reporter thread because we don't have threads
        thread_start( ext_gSettings );
#endif
    } else {
        // neither server nor client mode was specified
        // print usage and exit

#ifdef WIN32
        // In Win32 we also attempt to start a previously defined service
        // Starting in 2.0 to restart a previously defined service
        // you must call iperf with "iperf -D" or using the environment variable
        SERVICE_TABLE_ENTRY dispatchTable[] =
        {
            { TEXT(SZSERVICENAME), (LPSERVICE_MAIN_FUNCTION)service_main},
            { NULL, NULL}
        };

        // Only attempt to start the service if "-D" was specified
        if ( !isDaemon(ext_gSettings) ||
             // starting the service by SCM, there is no arguments will be passed in.
             // the arguments will pass into Service_Main entry.
             !StartServiceCtrlDispatcher(dispatchTable) )
            // If the service failed to start then print usage
#endif
        fprintf( stderr, usage_short, argv[0], argv[0] );

        return 0;
    }

    // wait for other (client, server) threads to complete
    thread_joinall();

    // all done!
    return 0;
} // end main
コード例 #4
0
ファイル: genome.c プロジェクト: Ikulagin/transmem
/* =============================================================================
 * main
 * =============================================================================
 */
int main (int argc, char** argv)
{
    int result = 0;
    TIMER_T start;
    TIMER_T stop;

    /* Initialization */
    parseArgs(argc, (char** const)argv);

    printf("Creating gene and segments... ");
    fflush(stdout);

    long geneLength = global_params[PARAM_GENE];
    long segmentLength = global_params[PARAM_SEGMENT];
    long minNumSegment = global_params[PARAM_NUMBER];
    long numThread = global_params[PARAM_THREAD];

    thread_startup(numThread);

    random_t* randomPtr = random_alloc();
    assert(randomPtr != NULL);
    random_seed(randomPtr, 0);

    gene_t* genePtr = gene_alloc(geneLength);
    assert( genePtr != NULL);
    gene_create(genePtr, randomPtr);
    char* gene = genePtr->contents;

    segments_t* segmentsPtr = segments_alloc(segmentLength, minNumSegment);
    assert(segmentsPtr != NULL);
    segments_create(segmentsPtr, genePtr, randomPtr);
    sequencer_t* sequencerPtr = sequencer_alloc(geneLength, segmentLength, segmentsPtr);
    assert(sequencerPtr != NULL);

    puts("done.");
    printf("Gene length     = %li\n", genePtr->length);
    printf("Segment length  = %li\n", segmentsPtr->length);
    printf("Number segments = %li\n", vector_getSize(segmentsPtr->contentsPtr));
    fflush(stdout);

    /* Benchmark */
    printf("Sequencing gene... ");
    fflush(stdout);
    TIMER_READ(start);
#ifdef OTM
#pragma omp parallel
    {
        sequencer_run(sequencerPtr);
    }
#else
    thread_start(sequencer_run, (void*)sequencerPtr);
#endif
    TIMER_READ(stop);
    puts("done.");
    printf("Time = %lf\n", TIMER_DIFF_SECONDS(start, stop));
    fflush(stdout);

    /* Check result */
    {
        char* sequence = sequencerPtr->sequence;
        result = strcmp(gene, sequence);
        printf("Sequence matches gene: %s\n", (result ? "no" : "yes"));
        if (result) {
            printf("gene     = %s\n", gene);
            printf("sequence = %s\n", sequence);
        }
        fflush(stdout);
        assert(strlen(sequence) >= strlen(gene));
    }

    /* Clean up */
    printf("Deallocating memory... ");
    fflush(stdout);
    sequencer_free(sequencerPtr);
    segments_free(segmentsPtr);
    gene_free(genePtr);
    random_free(randomPtr);
    puts("done.");
    fflush(stdout);

    thread_shutdown();

    return result;
}
コード例 #5
0
/*--------------------------------------------------------------------
 * ServiceStart
 *
 * each time starting the service, this is the entry point of the service.
 * Start the service, certainly it is on server-mode
 * 
 *-------------------------------------------------------------------- */
VOID ServiceStart (DWORD dwArgc, LPTSTR *lpszArgv) {
    
    // report the status to the service control manager.
    //
    if ( !ReportStatusToSCMgr(
                             SERVICE_START_PENDING, // service state
                             NO_ERROR,              // exit code
                             3000) )                 // wait hint
        goto clean;

    thread_Settings* ext_gSettings = new thread_Settings;

    // Initialize settings to defaults
    Settings_Initialize( ext_gSettings );
    // read settings from environment variables
    Settings_ParseEnvironment( ext_gSettings );
    // read settings from command-line parameters
    Settings_ParseCommandLine( dwArgc, lpszArgv, ext_gSettings );

    // report the status to the service control manager.
    //
    if ( !ReportStatusToSCMgr(
                             SERVICE_START_PENDING, // service state
                             NO_ERROR,              // exit code
                             3000) )                 // wait hint
        goto clean;

    // if needed, redirect the output into a specified file
    if ( !isSTDOUT( ext_gSettings ) ) {
        redirect( ext_gSettings->mOutputFileName );
    }

    // report the status to the service control manager.
    //
    if ( !ReportStatusToSCMgr(
                             SERVICE_START_PENDING, // service state
                             NO_ERROR,              // exit code
                             3000) )                 // wait hint
        goto clean;
    
    // initialize client(s)
    if ( ext_gSettings->mThreadMode == kMode_Client ) {
        client_init( ext_gSettings );
    }

    // start up the reporter and client(s) or listener
    {
        thread_Settings *into = NULL;
#ifdef HAVE_THREAD
        Settings_Copy( ext_gSettings, &into );
        into->mThreadMode = kMode_Reporter;
        into->runNow = ext_gSettings;
#else
        into = ext_gSettings;
#endif
        thread_start( into );
    }
    
    // report the status to the service control manager.
    //
    if ( !ReportStatusToSCMgr(
                             SERVICE_RUNNING,       // service state
                             NO_ERROR,              // exit code
                             0) )                    // wait hint
        goto clean;

    clean:
    // wait for other (client, server) threads to complete
    thread_joinall();
}
コード例 #6
0
ファイル: service.c プロジェクト: fishbaoz/wiced-emw3165
VOID ServiceStart (DWORD dwArgc, LPTSTR *lpszArgv) {
    
    // report the status to the service control manager.
    //
    if ( !ReportStatusToSCMgr(
                             SERVICE_START_PENDING, // service state
                             NO_ERROR,              // exit code
                             3000) )                 // wait hint
        goto clean;

    thread_Settings* ext_gSettings = (thread_Settings*) malloc(sizeof(thread_Settings));
	FAIL_errno( ext_gSettings == NULL, ( "No memory for thread_Settings ext_gSettings.\n" ), NULL );
	IPERF_DEBUGF( MEMALLOC_DEBUG | IPERF_DBG_TRACE, IPERF_MEMALLOC_MSG( ext_gSettings, sizeof(thread_Settings) ) );

    // Initialize settings to defaults
    Settings_Initialize( ext_gSettings );
#ifndef NO_ENVIRONMENT
    // read settings from environment variables
    Settings_ParseEnvironment( ext_gSettings );
#endif /* NO_ENVIRONMENT */
    // read settings from command-line parameters
    Settings_ParseCommandLine( dwArgc, lpszArgv, ext_gSettings );

    // report the status to the service control manager.
    //
    if ( !ReportStatusToSCMgr(
                             SERVICE_START_PENDING, // service state
                             NO_ERROR,              // exit code
                             3000) )                 // wait hint
        goto clean;

    // if needed, redirect the output into a specified file
    if ( !isSTDOUT( ext_gSettings ) ) {
        redirect( ext_gSettings->mOutputFileName );
    }

    // report the status to the service control manager.
    //
    if ( !ReportStatusToSCMgr(
                             SERVICE_START_PENDING, // service state
                             NO_ERROR,              // exit code
                             3000) )                 // wait hint
        goto clean;
    
    // initialize client(s)
    if ( ext_gSettings->mThreadMode == kMode_Client ) {
        client_init( ext_gSettings );
    }

    // start up the reporter and client(s) or listener
    {
        thread_Settings *into = NULL;
#ifdef HAVE_THREAD
        Settings_Copy( ext_gSettings, &into );
        into->mThreadMode = kMode_Reporter;
        into->runNow = ext_gSettings;
#else
        into = ext_gSettings;
#endif /* HAVE_THREAD */
        thread_start( into );
    }
    
    // report the status to the service control manager.
    //
    if ( !ReportStatusToSCMgr(
                             SERVICE_RUNNING,       // service state
                             NO_ERROR,              // exit code
                             0) )                    // wait hint
        goto clean;

    clean:
    // wait for other (client, server) threads to complete
    thread_joinall();
} // end ServiceStart
コード例 #7
0
ファイル: galeramon.c プロジェクト: DBMSRmutl/MaxScale
/**
 * Start the instance of the monitor, returning a handle on the monitor.
 *
 * This function creates a thread to execute the actual monitoring.
 *
 * @return A handle to use when interacting with the monitor
 */
static void *
startMonitor(void *arg, void* opt)
{
    MONITOR* mon = arg;
    GALERA_MONITOR *handle = mon->handle;
    CONFIG_PARAMETER* params = (CONFIG_PARAMETER*) opt;
    bool have_events = false, script_error = false;
    if (handle != NULL)
    {
        handle->shutdown = 0;
    }
    else
    {
        if ((handle = (GALERA_MONITOR *) malloc(sizeof(GALERA_MONITOR))) == NULL)
        {
            return NULL;
        }
        handle->shutdown = 0;
        handle->id = MONITOR_DEFAULT_ID;
        handle->disableMasterFailback = 0;
        handle->availableWhenDonor = 0;
        handle->disableMasterRoleSetting = 0;
        handle->master = NULL;
        handle->script = NULL;
        handle->use_priority = false;
        memset(handle->events, false, sizeof(handle->events));
        spinlock_init(&handle->lock);
    }


    while (params)
    {
        if (!strcmp(params->name, "disable_master_failback"))
        {
            handle->disableMasterFailback = config_truth_value(params->value);
        }
        else if (!strcmp(params->name, "available_when_donor"))
        {
            handle->availableWhenDonor = config_truth_value(params->value);
        }
        else if (!strcmp(params->name, "disable_master_role_setting"))
        {
            handle->disableMasterRoleSetting = config_truth_value(params->value);
        }
        else if (!strcmp(params->name, "use_priority"))
        {
            handle->use_priority = config_truth_value(params->value);
        }
        else if (!strcmp(params->name, "script"))
        {
            if (externcmd_can_execute(params->value))
            {
                free(handle->script);
                handle->script = strdup(params->value);
            }
            else
            {
                script_error = true;
            }
        }
        else if (!strcmp(params->name, "events"))
        {
            if (mon_parse_event_string((bool*) & handle->events,
                                       sizeof(handle->events), params->value) != 0)
            {
                script_error = true;
            }
            else
            {
                have_events = true;
            }
        }
        params = params->next;
    }
    if (script_error)
    {
        MXS_ERROR("Errors were found in the script configuration parameters "
                  "for the monitor '%s'. The script will not be used.", mon->name);
        free(handle->script);
        handle->script = NULL;
    }
    /** If no specific events are given, enable them all */
    if (!have_events)
    {
        memset(handle->events, true, sizeof(handle->events));
    }

    handle->tid = (THREAD) thread_start(monitorMain, mon);
    return handle;
}
コード例 #8
0
ファイル: mmmon.c プロジェクト: Nyte9/MaxScale
/**
 * Start the instance of the monitor, returning a handle on the monitor.
 *
 * This function creates a thread to execute the actual monitoring.
 *
 * @param arg	The current handle - NULL if first start
 * @return A handle to use when interacting with the monitor
 */
static	void 	*
startMonitor(void *arg,void* opt)
{
    MONITOR* mon = (MONITOR*)arg;
    MM_MONITOR *handle = mon->handle;
    CONFIG_PARAMETER* params = (CONFIG_PARAMETER*)opt;
    bool have_events = false,script_error = false;

    if (handle)
    {
	handle->shutdown = 0;
    }
    else
    {
	if ((handle = (MM_MONITOR *)malloc(sizeof(MM_MONITOR))) == NULL)
	    return NULL;
	handle->shutdown = 0;
	handle->id = MONITOR_DEFAULT_ID;
	handle->master = NULL;
	handle->script = NULL;
	memset(handle->events,false,sizeof(handle->events));
	spinlock_init(&handle->lock);
    }

    while(params)
    {
	if(!strcmp(params->name,"detect_stale_master"))
	{
	    handle->detectStaleMaster = config_truth_value(params->value);
	}
	else if(!strcmp(params->name,"script"))
	{
	    if(handle->script)
	    {
		free(handle->script);
	    }
	    if(access(params->value,X_OK) == 0)
	    {
		handle->script = strdup(params->value);
	    }
	    else
	    {
		script_error = true;
		if(access(params->value,F_OK) == 0)
		{
		skygw_log_write(LE,
			 "Error: The file cannot be executed: %s",
			 params->value);
		}
		else
		{
		skygw_log_write(LE,
			 "Error: The file cannot be found: %s",
			 params->value);
		}
		handle->script = NULL;
	    }
	}
	else if(!strcmp(params->name,"events"))
	{
	    if(mon_parse_event_string((bool*)&handle->events,sizeof(handle->events),params->value) != 0)
		script_error = true;
	    else
		have_events = true;
	}
	params = params->next;
    }
    if(script_error)
    {
	skygw_log_write(LE,"Error: Errors were found in the script configuration parameters "
		"for the monitor '%s'. The script will not be used.",mon->name);
	free(handle->script);
	handle->script = NULL;
    }
    /** If no specific events are given, enable them all */
    if(!have_events)
    {
	memset(handle->events,true,sizeof(handle->events));
    }
    handle->tid = (THREAD)thread_start(monitorMain, mon);
    return handle;
}
コード例 #9
0
ファイル: ssca2.c プロジェクト: HPDCS/htmMCATS
MAIN(argc, argv)
{
    GOTO_REAL();

    SETUP_NUMBER_TASKS(10);

    /*
     * Tuple for Scalable Data Generation
     * stores startVertex, endVertex, long weight and other info
     */
    graphSDG* SDGdata;

    /*
     * The graph data structure for this benchmark - see defs.h
     */
    graph* G;

#ifdef ENABLE_KERNEL2
    /*
     * Kernel 2
     */
    edge* maxIntWtList;
    edge* soughtStrWtList;
    long maxIntWtListSize;
    long soughtStrWtListSize;

#endif /* ENABLE_KERNEL2 */

#ifdef ENABLE_KERNEL3

#  ifndef ENABLE_KERNEL2
#    error KERNEL3 requires KERNEL2
#  endif

    /*
     * Kernel 3
     */
    V*   intWtVList  = NULL;
    V*   strWtVList  = NULL;
    Vl** intWtVLList = NULL;
    Vl** strWtVLList = NULL;
    Vd*  intWtVDList = NULL;
    Vd*  strWtVDList = NULL;

#endif /* ENABLE_KERNEL3 */

    double totalTime = 0.0;

    /* -------------------------------------------------------------------------
     * Preamble
     * -------------------------------------------------------------------------
     */

    /*
     * User Interface: Configurable parameters, and global program control
     */

    getUserParameters(argc, (char** const) argv);

    SIM_GET_NUM_CPU(THREADS);
    TM_STARTUP(THREADS, 0);
    P_MEMORY_STARTUP(THREADS);
    SETUP_NUMBER_THREADS(THREADS);
    thread_startup(THREADS);

double time_total = 0.0;
int repeat = REPEATS;
for (; repeat > 0; --repeat) {

    SDGdata = (graphSDG*)malloc(sizeof(graphSDG));
    assert(SDGdata);

    genScalData_seq(SDGdata);

    G = (graph*)malloc(sizeof(graph));
    assert(G);

    computeGraph_arg_t computeGraphArgs;
    computeGraphArgs.GPtr       = G;
    computeGraphArgs.SDGdataPtr = SDGdata;

TIMER_T start;
    TIMER_READ(start);

    GOTO_SIM();
    thread_start(computeGraph, (void*)&computeGraphArgs);
    GOTO_REAL();
TIMER_T stop;
    TIMER_READ(stop);
double time_tmp = TIMER_DIFF_SECONDS(start, stop);
PRINT_STATS();
time_total += time_tmp;
}

totalTime += time_total;


#ifdef ENABLE_KERNEL2

    /* -------------------------------------------------------------------------
     * Kernel 2 - Find Max weight and sought string
     * -------------------------------------------------------------------------
     */

    printf("\nKernel 2 - getStartLists() beginning execution...\n");

    maxIntWtListSize = 0;
    soughtStrWtListSize = 0;
    maxIntWtList = (edge*)malloc(sizeof(edge));
    assert(maxIntWtList);
    soughtStrWtList = (edge*)malloc(sizeof(edge));
    assert(soughtStrWtList);

    getStartLists_arg_t getStartListsArg;
    getStartListsArg.GPtr                = G;
    getStartListsArg.maxIntWtListPtr     = &maxIntWtList;
    getStartListsArg.maxIntWtListSize    = &maxIntWtListSize;
    getStartListsArg.soughtStrWtListPtr  = &soughtStrWtList;
    getStartListsArg.soughtStrWtListSize = &soughtStrWtListSize;

    TIMER_READ(start);

    GOTO_SIM();
#ifdef OTM
#pragma omp parallel
    {
        getStartLists((void*)&getStartListsArg);
    }
#else
    thread_start(getStartLists, (void*)&getStartListsArg);
#endif
    GOTO_REAL();

TIMER_T stop;
    TIMER_READ(stop);

    time = TIMER_DIFF_SECONDS(start, stop);
    totalTime += time;

    printf("\n\tgetStartLists() completed execution.\n");
    printf("\nTime taken for kernel 2 is %9.6f sec.\n\n", time);

#endif /* ENABLE_KERNEL2 */

#ifdef ENABLE_KERNEL3

    /* -------------------------------------------------------------------------
     * Kernel 3 - Graph Extraction
     * -------------------------------------------------------------------------
     */

    printf("\nKernel 3 - findSubGraphs() beginning execution...\n");

    if (K3_DS == 0) {

        intWtVList = (V*)malloc(G->numVertices * maxIntWtListSize * sizeof(V));
        assert(intWtVList);
        strWtVList = (V*)malloc(G->numVertices * soughtStrWtListSize * sizeof(V));
        assert(strWtVList);

        findSubGraphs0_arg_t findSubGraphs0Arg;
        findSubGraphs0Arg.GPtr                = G;
        findSubGraphs0Arg.intWtVList          = intWtVList;
        findSubGraphs0Arg.strWtVList          = strWtVList;
        findSubGraphs0Arg.maxIntWtList        = maxIntWtList;
        findSubGraphs0Arg.maxIntWtListSize    = maxIntWtListSize;
        findSubGraphs0Arg.soughtStrWtList     = soughtStrWtList;
        findSubGraphs0Arg.soughtStrWtListSize = soughtStrWtListSize;

        TIMER_READ(start);

        GOTO_SIM();
#ifdef OTM
#pragma omp parallel
        {
            findSubGraphs0((void*)&findSubGraphs0Arg);
        }
#else
        thread_start(findSubGraphs0, (void*)&findSubGraphs0Arg);
#endif
        GOTO_REAL();

        TIMER_READ(stop);

    } else if (K3_DS == 1) {

        intWtVLList = (Vl**)malloc(maxIntWtListSize * sizeof(Vl*));
        assert(intWtVLList);
        strWtVLList = (Vl**)malloc(soughtStrWtListSize * sizeof(Vl*));
        assert(strWtVLList);

        findSubGraphs1_arg_t findSubGraphs1Arg;
        findSubGraphs1Arg.GPtr                = G;
        findSubGraphs1Arg.intWtVLList         = intWtVLList;
        findSubGraphs1Arg.strWtVLList         = strWtVLList;
        findSubGraphs1Arg.maxIntWtList        = maxIntWtList;
        findSubGraphs1Arg.maxIntWtListSize    = maxIntWtListSize;
        findSubGraphs1Arg.soughtStrWtList     = soughtStrWtList;
        findSubGraphs1Arg.soughtStrWtListSize = soughtStrWtListSize;

        TIMER_READ(start);

        GOTO_SIM();
#ifdef OTM
#pragma omp parallel
        {
            findSubGraphs1((void*)&findSubGraphs1Arg);
        }
#else
        thread_start(findSubGraphs1, (void*)&findSubGraphs1Arg);
#endif
        GOTO_REAL();

        TIMER_READ(stop);

        /*  Verification
        on_one_thread {
          for (i=0; i<maxIntWtListSize; i++) {
            printf("%ld -- ", i);
            currV = intWtVLList[i];
            while (currV != NULL) {
              printf("[%ld %ld] ", currV->num, currV->depth);
              currV = currV->next;
            }
            printf("\n");
          }

          for (i=0; i<soughtStrWtListSize; i++) {
            printf("%ld -- ", i);
            currV = strWtVLList[i];
            while (currV != NULL) {
              printf("[%ld %ld] ", currV->num, currV->depth);
              currV = currV->next;
            }
            printf("\n");
          }

        }
        */

    } else if (K3_DS == 2) {

        intWtVDList = (Vd *) malloc(maxIntWtListSize * sizeof(Vd));
        assert(intWtVDList);
        strWtVDList = (Vd *) malloc(soughtStrWtListSize * sizeof(Vd));
        assert(strWtVDList);

        findSubGraphs2_arg_t findSubGraphs2Arg;
        findSubGraphs2Arg.GPtr                = G;
        findSubGraphs2Arg.intWtVDList         = intWtVDList;
        findSubGraphs2Arg.strWtVDList         = strWtVDList;
        findSubGraphs2Arg.maxIntWtList        = maxIntWtList;
        findSubGraphs2Arg.maxIntWtListSize    = maxIntWtListSize;
        findSubGraphs2Arg.soughtStrWtList     = soughtStrWtList;
        findSubGraphs2Arg.soughtStrWtListSize = soughtStrWtListSize;

        TIMER_READ(start);

        GOTO_SIM();
#ifdef OTM
#pragma omp parallel
        {
            findSubGraphs2((void*)&findSubGraphs2Arg);
        }
#else
        thread_start(findSubGraphs2, (void*)&findSubGraphs2Arg);
#endif
        GOTO_REAL();

        TIMER_READ(stop);

        /* Verification */
        /*
        on_one_thread {
          printf("\nInt weight sub-graphs \n");
          for (i=0; i<maxIntWtListSize; i++) {
            printf("%ld -- ", i);
            for (j=0; j<intWtVDList[i].numArrays; j++) {
              printf("\n [Array %ld] - \n", j);
              for (k=0; k<intWtVDList[i].arraySize[j]; k++) {
                printf("[%ld %ld] ", intWtVDList[i].vList[j][k].num, intWtVDList[i].vList[j][k].depth);
              }

            }
            printf("\n");
          }

          printf("\nStr weight sub-graphs \n");
          for (i=0; i<soughtStrWtListSize; i++) {
            printf("%ld -- ", i);
            for (j=0; j<strWtVDList[i].numArrays; j++) {
              printf("\n [Array %ld] - \n", j);
              for (k=0; k<strWtVDList[i].arraySize[j]; k++) {
                printf("[%ld %ld] ", strWtVDList[i].vList[j][k].num, strWtVDList[i].vList[j][k].depth);
              }

            }
            printf("\n");
          }

        }
       */

    } else {

        assert(0);

    }

    time = TIMER_DIFF_SECONDS(start, stop);
    totalTime += time;

    printf("\n\tfindSubGraphs() completed execution.\n");
    printf("\nTime taken for kernel 3 is %9.6f sec.\n\n", time);

#endif /* ENABLE_KERNEL3 */

#ifdef ENABLE_KERNEL4

    /* -------------------------------------------------------------------------
     * Kernel 4 - Graph Clustering
     * -------------------------------------------------------------------------
     */

    printf("\nKernel 4 - cutClusters() beginning execution...\n");

    TIMER_READ(start);

    GOTO_SIM();
#ifdef OTM
#pragma omp parallel
    {
        cutClusters((void*)G);
    }
#else
    thread_start(cutClusters, (void*)G);
#endif
    GOTO_REAL();

    TIMER_READ(stop);

    time = TIMER_DIFF_SECONDS(start, stop);
    totalTime += time;

    printf("\n\tcutClusters() completed execution.\n");
    printf("\nTime taken for Kernel 4 is %9.6f sec.\n\n", time);

#endif /* ENABLE_KERNEL4 */

    printf("Time = %9.6f \n", totalTime);

    /* -------------------------------------------------------------------------
     * Cleanup
     * -------------------------------------------------------------------------
     */

    P_FREE(G->outDegree);
    P_FREE(G->outVertexIndex);
    P_FREE(G->outVertexList);
    P_FREE(G->paralEdgeIndex);
    P_FREE(G->inDegree);
    P_FREE(G->inVertexIndex);
    P_FREE(G->inVertexList);
    P_FREE(G->intWeight);
    P_FREE(G->strWeight);

#ifdef ENABLE_KERNEL3

    LONGINT_T i;
    LONGINT_T j;
    Vl* currV;
    Vl* tempV;

    if (K3_DS == 0) {
        P_FREE(strWtVList);
        P_FREE(intWtVList);
    }

    if (K3_DS == 1) {
        for (i = 0; i < maxIntWtListSize; i++) {
            currV = intWtVLList[i];
            while (currV != NULL) {
                tempV = currV->next;
                P_FREE(currV);
                currV = tempV;
            }
        }
        for (i = 0; i < soughtStrWtListSize; i++) {
            currV = strWtVLList[i];
            while (currV != NULL) {
                tempV = currV->next;
                P_FREE(currV);
                currV = tempV;
            }
        }
        P_FREE(strWtVLList);
        P_FREE(intWtVLList);
    }

    if (K3_DS == 2) {
        for (i = 0; i < maxIntWtListSize; i++) {
            for (j = 0; j < intWtVDList[i].numArrays; j++) {
                P_FREE(intWtVDList[i].vList[j]);
            }
            P_FREE(intWtVDList[i].vList);
            P_FREE(intWtVDList[i].arraySize);
        }
        for (i = 0; i < soughtStrWtListSize; i++) {
            for (j = 0; j < strWtVDList[i].numArrays; j++) {
                P_FREE(strWtVDList[i].vList[j]);
            }
            P_FREE(strWtVDList[i].vList);
            P_FREE(strWtVDList[i].arraySize);
        }
        P_FREE(strWtVDList);
        P_FREE(intWtVDList);
    }

    P_FREE(soughtStrWtList);
    P_FREE(maxIntWtList);

#endif /* ENABLE_KERNEL2 */

    P_FREE(SOUGHT_STRING);
    P_FREE(G);
    P_FREE(SDGdata);

    TM_SHUTDOWN();
    P_MEMORY_SHUTDOWN();

    GOTO_SIM();

    thread_shutdown();

    MAIN_RETURN(0);
}
コード例 #10
0
ファイル: barbershop.c プロジェクト: necto/verifast
void main()
    //@ requires obs(nil);
    //@ ensures obs(nil);
{
    //@ close create_mutex_ghost_args(0,nil);
    struct mutex *m = create_mutex();
    
    //@ int gba = new_ctr();
    //@ close create_condvar_ghost_args(m,1,false,vtrn(gba));
    struct condvar *cbarber = create_condvar();

    //@ int gch = new_ctr();
    //@ close create_condvar_ghost_args(m,2,false,vtrn(gch));
    struct condvar *cchair = create_condvar();

    //@ int gdo = new_ctr();
    //@ close create_condvar_ghost_args(m,3,false,vtrn(gdo));
    struct condvar *cdoor = create_condvar();
    
    //@ int gcu = new_ctr();
    //@ close create_condvar_ghost_args(m,4,false,vtrn(gcu));
    struct condvar *ccustomer = create_condvar();
    
    struct barbershop *b = malloc(sizeof(struct barbershop));
    if (b==0)
      abort();
    b->m = m;
    b->barber = 0;
    b->chair = 0;
    b->door = 0;
    b->cbarber = cbarber;
    b->cchair = cchair;
    b->cdoor = cdoor;
    b->ccustomer = ccustomer;
    //@ b->gba = gba;
    //@ b->gch = gch;
    //@ b->gdo = gdo;
    //@ b->gcu = gcu;
    
    //@ leak [_]b->cbarber |-> _;
    //@ leak [_]b->cchair |-> _;
    //@ leak [_]b->cdoor |-> _;
    //@ leak [_]b->ccustomer |-> _;            
    //@ leak [_]b->m |-> _;  
    //@ leak [_]b->gba |-> _;               
    //@ leak [_]b->gch |-> _;               
    //@ leak [_]b->gdo |-> _;               
    //@ leak [_]b->gcu |-> _;               
    //@ leak [_]malloc_block_barbershop(_);
    
    //@ close init_mutex_ghost_args(barbershop(b));
    //@ g_chrgu(cbarber);    
    //@ g_chrgu(cchair);    
    //@ g_chrgu(cdoor);    
    //@ g_chrgu(ccustomer);    
    //@ inc_ctr(gba);
    //@ inc_ctr(gch);
    //@ inc_ctr(gdo);
    //@ inc_ctr(gcu);
    //@ inc_ctr(gcu);
    //@ close barbershop(b)(empb,finc(finc(finc(finc(empb,cbarber),cchair),cdoor),ccustomer));    
    //@ init_mutex(m);
    //@ leak [_]mutex(m);
    
    //@ close unprotected_permissions(b,_,_,_,_,_,_,_,_,_);
    //@ close thread_run_data(get_haircut_thread)(cons(cchair,(cons(ccustomer,nil))),b);
    thread_start(get_haircut_thread, b);

    //@ close unprotected_permissions(b,_,_,_,_,_,_,_,_,_);
    //@ close thread_run_data(get_next_customer_thread)(cons(cbarber,nil),b);
    thread_start(get_next_customer_thread, b);

    //@ close unprotected_permissions(b,_,_,_,_,_,_,_,_,_);
    //@ close thread_run_data(finished_cut_customer_thread)(cons(cdoor,nil),b);
    thread_start(finished_cut_customer_thread, b);
}
コード例 #11
0
void shutDownAfter(int seconds) {
    wait = seconds;
    thread tr = thread_create(kill);
    thread_start(tr);
}
コード例 #12
0
ファイル: genome.c プロジェクト: hlitz/rstm_sitevm_dune
/* =============================================================================
 * main
 * =============================================================================
 */
MAIN (argc,argv)
{
    TIMER_T start;
    TIMER_T stop;

    /* Initialization */
    parseArgs(argc, (char** const)argv);
    SIM_GET_NUM_CPU(global_params[PARAM_THREAD]);

    printf("Creating gene and segments... ");
    fflush(stdout);

    long geneLength = global_params[PARAM_GENE];
    long segmentLength = global_params[PARAM_SEGMENT];
    long minNumSegment = global_params[PARAM_NUMBER];
    long numThread = global_params[PARAM_THREAD];


    random_t* randomPtr;
    gene_t* genePtr;
    char* gene;
    segments_t* segmentsPtr;
    sequencer_t* sequencerPtr;

    TM_STARTUP(numThread);
    P_MEMORY_STARTUP(numThread);
    TM_THREAD_ENTER();

    //    TM_BEGIN();
    randomPtr= random_alloc();
    assert(randomPtr != NULL);
    random_seed(randomPtr, 0);

    genePtr = gene_alloc(geneLength);
    assert( genePtr != NULL);
    gene_create(genePtr, randomPtr);
    gene = genePtr->contents;

    segmentsPtr = segments_alloc(segmentLength, minNumSegment);
    assert(segmentsPtr != NULL);
    segments_create(segmentsPtr, genePtr, randomPtr);
    sequencerPtr = sequencer_alloc(geneLength, segmentLength, segmentsPtr);
    assert(sequencerPtr != NULL);
    //TM_END();
    thread_startup(numThread);
    puts("done.");
    printf("Gene length     = %li\n", genePtr->length);
    printf("Segment length  = %li\n", segmentsPtr->length);
    printf("Number segments = %li\n", vector_getSize(segmentsPtr->contentsPtr));
    fflush(stdout);

    /* Benchmark */
    printf("Sequencing gene... ");
    fflush(stdout);
    // NB: Since ASF/PTLSim "REAL" is native execution, and since we are using
    //     wallclock time, we want to be sure we read time inside the
    //     simulator, or else we report native cycles spent on the benchmark
    //     instead of simulator cycles.
    GOTO_SIM();
    TIMER_READ(start);
#ifdef OTM
#pragma omp parallel
    {
        sequencer_run(sequencerPtr);
    }
#else
    thread_start(sequencer_run, (void*)sequencerPtr);
#endif
    TIMER_READ(stop);
    // NB: As above, timer reads must be done inside of the simulated region
    //     for PTLSim/ASF
    GOTO_REAL();
    puts("done.");
    printf("Time = %lf\n", TIMER_DIFF_SECONDS(start, stop));
    fflush(stdout);

    /* Check result */
    {
      char* sequence;
      int result;
      //TM_BEGIN();
      sequence= sequencerPtr->sequence;
      result = strcmp(gene, sequence);
      //TM_END();
        printf("Sequence matches gene: %s\n", (result ? "no" : "yes"));
        if (result) {
            printf("gene     = %s\n", gene);
            printf("sequence = %s\n", sequence);
        }
        fflush(stdout);
        assert(strlen(sequence) >= strlen(gene));
    }

    /* Clean up */
    printf("Deallocating memory... ");
    fflush(stdout);
    sequencer_free(sequencerPtr);
    segments_free(segmentsPtr);
    gene_free(genePtr);
    random_free(randomPtr);
    puts("done.");
    fflush(stdout);

    TM_SHUTDOWN();
    P_MEMORY_SHUTDOWN();

    thread_shutdown();

    MAIN_RETURN(0);
}
コード例 #13
0
ファイル: main.cpp プロジェクト: fishbaoz/wiced-emw3165
/* -------------------------------------------------------------------
 * main()
 *      Entry point into Iperf
 *
 * sets up signal handlers
 * initialize global locks and conditions
 * parses settings from environment and command line
 * starts up server or client thread
 * waits for all threads to complete
 * ------------------------------------------------------------------- */
#ifdef __cplusplus
extern "C"
#endif /* __cplusplus */
int IPERF_MAIN( int argc, char **argv ) {
#ifdef NO_EXIT
    should_exit = 0;
#endif /* NO_EXIT */
#ifdef IPERF_DEBUG
    debug_init();
#endif /* IPERF_DEBUG */

#ifndef NO_INTERRUPTS
#ifdef WIN32
    setsigalrmfunc(call_sigalrm);
#endif /* WIN32 */

    // Set SIGTERM and SIGINT to call our user interrupt function
    my_signal( SIGTERM, Sig_Interupt );
    my_signal( SIGINT,  Sig_Interupt );
    my_signal( SIGALRM,  Sig_Interupt );

#ifndef WIN32
    // Ignore broken pipes
    signal(SIGPIPE,SIG_IGN);
#else
    // Start winsock
    WORD wVersionRequested;
    WSADATA wsaData;

    // Using MAKEWORD macro, Winsock version request 2.2
    wVersionRequested = MAKEWORD(2, 2);

    int rc = WSAStartup( wVersionRequested, &wsaData );
    WARN_errno( rc == SOCKET_ERROR, ( "WSAStartup failed.\n" ) );
	if (rc != 0) {
	    fprintf(stderr, "The Winsock DLL was not found!\n");
		return 1;
	}

    /*
     * Confirm that the WinSock DLL supports 2.2. Note that if the DLL supports
	 * versions greater than 2.2 in addition to 2.2, it will still return 2.2 in
	 * wVersion since that is the version we requested.
     */
    if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2 ) {
        /* Tell the user that we could not find a usable WinSock DLL. */
        fprintf(stderr, "The DLL does not support the Winsock version %u.%u!\n", LOBYTE(wsaData.wVersion),HIBYTE(wsaData.wVersion));
        WSACleanup();
        return 1;
    }

    // Tell windows we want to handle our own signals
    SetConsoleCtrlHandler( sig_dispatcher, true );
#endif /* WIN32 */
#endif /* NO_INTERRUPTS */

    // Initialize global mutexes and conditions
    IPERF_DEBUGF( CONDITION_DEBUG | IPERF_DBG_TRACE, ( "Initializing report condition.\n" ) );
    Condition_Initialize ( &ReportCond );
    IPERF_DEBUGF( CONDITION_DEBUG | IPERF_DBG_TRACE, ( "Initializing report done condition.\n" ) );
    Condition_Initialize ( &ReportDoneCond );
    IPERF_DEBUGF( MUTEX_DEBUG | IPERF_DBG_TRACE, ( "Initializing group condition mutex.\n" ) );
    Mutex_Initialize( &groupCond );
    IPERF_DEBUGF( MUTEX_DEBUG | IPERF_DBG_TRACE, ( "Initializing clients mutex.\n" ) );
    Mutex_Initialize( &clients_mutex );

    // Initialize the thread subsystem
    IPERF_DEBUGF( THREAD_DEBUG | IPERF_DBG_TRACE, ( "Initializing the thread subsystem.\n" ) );
    thread_init( );

    // Initialize the interrupt handling thread to 0
    sThread = thread_zeroid();

#ifndef NO_EXIT
    // perform any cleanup when quitting Iperf
    atexit( cleanup );
#endif /* NO_EXIT */

    // Allocate the "global" settings
    thread_Settings *ext_gSettings = (thread_Settings*) malloc( sizeof( thread_Settings ) );
    FAIL( ext_gSettings == NULL, ( "Unable to allocate memory for thread_Settings ext_gSettings.\n" ), NULL );
    IPERF_DEBUGF( MEMALLOC_DEBUG, IPERF_MEMALLOC_MSG( ext_gSettings, sizeof( thread_Settings ) ) );

    // Initialize settings to defaults
    Settings_Initialize( ext_gSettings );
#ifndef NO_ENVIRONMENT
    // read settings from environment variables
    Settings_ParseEnvironment( ext_gSettings );
#endif /* NO_ENVIORNMENT */
    // read settings from command-line parameters
    Settings_ParseCommandLine( argc, argv, ext_gSettings );

#ifdef NO_EXIT
    if (should_exit) {
        IPERF_DEBUGF( MEMFREE_DEBUG | IPERF_DBG_TRACE, IPERF_MEMFREE_MSG( ext_gSettings ) );
        FREE_PTR( ext_gSettings );

        IPERF_DEBUGF( CONDITION_DEBUG | IPERF_DBG_TRACE, ( "Destroying report condition.\n" ) );
        Condition_Destroy( &ReportCond );
        IPERF_DEBUGF( CONDITION_DEBUG | IPERF_DBG_TRACE, ( "Destroying report done condition.\n" ) );
        Condition_Destroy( &ReportDoneCond );
        IPERF_DEBUGF( MUTEX_DEBUG | IPERF_DBG_TRACE, ( "Destroying group condition mutex.\n" ) );
        Mutex_Destroy( &groupCond );
        IPERF_DEBUGF( MUTEX_DEBUG | IPERF_DBG_TRACE, ( "Destroying clients mutex.\n" ) );
        Mutex_Destroy( &clients_mutex );

        return 0;
    }
#endif /* NO_EXIT */

    // Check for either having specified client or server
    if ( ext_gSettings->mThreadMode == kMode_Client 
         || ext_gSettings->mThreadMode == kMode_Listener ) {
#ifdef WIN32
#ifndef NO_DAEMON
        // Start the server as a daemon
        // Daemon mode for non-windows in handled
        // in the listener_spawn function
        if ( isDaemon( ext_gSettings ) ) {
            CmdInstallService(argc, argv);
            return 0;
        }
#endif /* NO_DAEMON */

#ifndef NO_SERVICE
        // Remove the Windows service if requested
        if ( isRemoveService( ext_gSettings ) ) {
            // remove the service
            if ( CmdRemoveService() ) {
                fprintf(stderr, "IPerf Service is removed.\n");
                return 0;
            }
        }
#endif /* NO_SERVICE */
#endif /* WIN32 */
        // initialize client(s)
        if ( ext_gSettings->mThreadMode == kMode_Client ) {
            IPERF_DEBUGF( CLIENT_DEBUG | LISTENER_DEBUG | IPERF_DBG_TRACE, ( "Initializing client(s)...\n" ) );
            client_init( ext_gSettings );
        }

#ifdef HAVE_THREAD
        // start up the reporter and client(s) or listener
        thread_Settings *into = NULL;
        // Create the settings structure for the reporter thread
        IPERF_DEBUGF( CLIENT_DEBUG | LISTENER_DEBUG | REPORTER_DEBUG | IPERF_DBG_TRACE, ( "Creating the settings structure for the reporter thread.\n" ) );
        Settings_Copy( ext_gSettings, &into );
        into->mThreadMode = kMode_Reporter;

        // Have the reporter launch the client or listener
        IPERF_DEBUGF( CLIENT_DEBUG | LISTENER_DEBUG | IPERF_DBG_TRACE, ( "Setting the reporter to launch the client or listener before launching itself.\n" ) );
        into->runNow = ext_gSettings;
        
        // Start all the threads that are ready to go
        IPERF_DEBUGF( THREAD_DEBUG | IPERF_DBG_TRACE, ( "Starting all the threads...\n" ) );
        thread_start( into );
#else
        // No need to make a reporter thread because we don't have threads
        IPERF_DEBUGF( THREAD_DEBUG | IPERF_DBG_TRACE, ( "Starting iperf in a single thread...\n" ) );
        thread_start( ext_gSettings );
#endif /* HAVE_THREAD */
    } else {
        // neither server nor client mode was specified
        // print usage and exit

#ifdef WIN32
        // In Win32 we also attempt to start a previously defined service
        // Starting in 2.0 to restart a previously defined service
        // you must call iperf with "iperf -D" or using the environment variable
        SERVICE_TABLE_ENTRY dispatchTable[] =
        {
            { TEXT((char *) SZSERVICENAME), (LPSERVICE_MAIN_FUNCTION)service_main},
            { NULL, NULL}
        };

#ifndef NO_DAEMON
        // Only attempt to start the service if "-D" was specified
        if ( !isDaemon(ext_gSettings) ||
             // starting the service by SCM, there is no arguments will be passed in.
             // the arguments will pass into Service_Main entry.
             !StartServiceCtrlDispatcher(dispatchTable) )
            // If the service failed to start then print usage
#endif /* NO_DAEMON */
#endif /* WIN32 */
        fprintf( stderr, usage_short, argv[0], argv[0] );

        return 0;
    }

    // wait for other (client, server) threads to complete
//    IPERF_DEBUGF( THREAD_DEBUG | IPERF_DBG_TRACE, ( "Waiting for other (client, server) threads to complete...\n" ) );
//    thread_joinall();
    
#ifdef NO_EXIT
	/* We can't run the atexit function */
#ifdef WIN32
    // Shutdown Winsock
    WSACleanup();
#endif /* WIN32 */
    // clean up the list of clients
    Iperf_destroy ( &clients );

    // shutdown the thread subsystem
    IPERF_DEBUGF( THREAD_DEBUG | IPERF_DBG_TRACE, ( "Deinitializing the thread subsystem.\n" ) );

    IPERF_DEBUGF( CONDITION_DEBUG | IPERF_DBG_TRACE, ( "Destroying report condition.\n" ) );
    Condition_Destroy( &ReportCond );
    IPERF_DEBUGF( CONDITION_DEBUG | IPERF_DBG_TRACE, ( "Destroying report done condition.\n" ) );
    Condition_Destroy( &ReportDoneCond );
    IPERF_DEBUGF( MUTEX_DEBUG | IPERF_DBG_TRACE, ( "Destroying group condition mutex.\n" ) );
    Mutex_Destroy( &groupCond );
    IPERF_DEBUGF( MUTEX_DEBUG | IPERF_DBG_TRACE, ( "Destroying clients mutex.\n" ) );
    Mutex_Destroy( &clients_mutex );

#ifdef IPERF_DEBUG
    debug_init();
#endif /* IPERF_DEBUG */
#endif /* NO_EXIT */
	
    // all done!
    IPERF_DEBUGF( IPERF_DBG_TRACE | IPERF_DBG_STATE, ( "Done!\n" ) );
    return 0;
} // end main
コード例 #14
0
ファイル: yada.c プロジェクト: jaingaurav/rstm
/* =============================================================================
 * main
 * =============================================================================
 */
MAIN(argc, argv)
{
    /*
     * Initialization
     */

    parseArgs(argc, (char** const)argv);
    SIM_GET_NUM_CPU(global_numThread);
    TM_STARTUP(global_numThread);
    P_MEMORY_STARTUP(global_numThread);
    thread_startup(global_numThread);
    global_meshPtr = mesh_alloc();
    assert(global_meshPtr);
    printf("Angle constraint = %lf\n", global_angleConstraint);
    printf("Reading input... ");
    long initNumElement = mesh_read(global_meshPtr, (char*)global_inputPrefix);
    puts("done.");
    global_workHeapPtr = heap_alloc(1, &yada_heapcompare);
    assert(global_workHeapPtr);
    long initNumBadElement = initializeWork(global_workHeapPtr, global_meshPtr);

    printf("Initial number of mesh elements = %li\n", initNumElement);
    printf("Initial number of bad elements  = %li\n", initNumBadElement);
    printf("Starting triangulation...");
    fflush(stdout);

    /*
     * Run benchmark
     */

    // NB: Since ASF/PTLSim "REAL" is native execution, and since we are using
    //     wallclock time, we want to be sure we read time inside the
    //     simulator, or else we report native cycles spent on the benchmark
    //     instead of simulator cycles.
    GOTO_SIM();
    TIMER_T start;
    TIMER_READ(start);
#ifdef OTM
#pragma omp parallel
    {
        process();
    }
#else
    thread_start((void(*)(void*))process, NULL);
#endif
    TIMER_T stop;
    TIMER_READ(stop);
    // NB: As above, timer reads must be done inside of the simulated region
    //     for PTLSim/ASF
    GOTO_REAL();

    puts(" done.");
    printf("Elapsed time                    = %0.3lf\n",
           TIMER_DIFF_SECONDS(start, stop));
    fflush(stdout);

    /*
     * Check solution
     */

    long finalNumElement = initNumElement + global_totalNumAdded;
    printf("Final mesh size                 = %li\n", finalNumElement);
    printf("Number of elements processed    = %li\n", global_numProcess);
    fflush(stdout);

#if 1
    bool isSuccess = mesh_check(global_meshPtr, finalNumElement);
#else
    bool isSuccess = true;
#endif
    printf("Final mesh is %s\n", (isSuccess ? "valid." : "INVALID!"));
    fflush(stdout);
    assert(isSuccess);

    /*
     * TODO: deallocate mesh and work heap
     */
    TM_SHUTDOWN();
    P_MEMORY_SHUTDOWN();

    GOTO_SIM();

    thread_shutdown();

    MAIN_RETURN(0);
}
コード例 #15
0
 void MdiEditor::NewProject(bool flag)
 {
 	clear();
	if (!flag)
	  	pro_path = QFileDialog::getExistingDirectory (this);
  	if(!pro_path.isNull())
  	{

  		if(!ReadXmlFile(pro_path+"\\settings.xml"))//exist

  		{

  			QFile::remove(pro_path+"\\result.html");
  			QFile::copy("template.html",pro_path+"\\result.html");


  			//load two images
  			QString ImagePathName = QFileDialog::getOpenFileName(
  				this,
  				"Load Image1",
  				QDir::currentPath(),
  				"Image files (*.bmp *.png *.jpg *.gif);All files(*.*)");
  			image1=cv::imread(ImagePathName.toLatin1().data());
			if(image1.rows==0)
 				return;
 			parameters->fname0=(const char *)ImagePathName.toLocal8Bit();
			parameters[0].mask1=Mat::zeros(image1.rows,image1.cols,CV_8UC3);

  			ImagePathName = QFileDialog::getOpenFileName(
  					this,
  					"Load Image2",
  					QDir::currentPath(),
  					"Image files (*.bmp *.png *.jpg *.gif);All files(*.*)");
  			image2=cv::imread(ImagePathName.toLatin1().data());
 			if(image2.rows==0)
 				return;
			parameters->fname1=(const char *)ImagePathName.toLocal8Bit();
  			parameters[0].mask2=Mat::zeros(image2.rows,image2.cols,CV_8UC3);

			QString item;
			item.sprintf("&layer %d",0);
			show_layer[0]=new QAction(item.toLatin1().data(), this);
			layer_view->addAction(show_layer[0]);
			show_layer[0]->setCheckable(true);
			connect(show_layer[0],SIGNAL(triggered()),this,SLOT(Layer0()));

			layer_num++;
		}

		imageEditorL->setImage(image1);
		imageEditorR->setImage(image2);
		imageEditorM->setImage(imageEditorL->_image,imageEditorR->_image);
		ctrbar->_status=1;
		mod=1;

		for(int i=0;i<layer_num;i++)
		{
			int n=log((float)MIN(image1.cols,image1.rows))/log(2.0f)-log((float)parameters[i].start_res)/log(2.0f)+1;
  			pyramids[i].build_pyramid(image1,image2,parameters[i],n,i,gpu_cap);
		}
		thread_start(layer_index);

		Changelayer();
 	}
 }
コード例 #16
0
DWORD WINAPI
#else
void*
#endif /* HAVE_WIN32_THREAD */
thread_run_wrapper( void* paramPtr ) {
    struct thread_Settings* thread = (struct thread_Settings*) paramPtr;
    IPERF_DEBUGF( THREAD_DEBUG | IPERF_DBG_TRACE | IPERF_DBG_STATE, ( "%s thread is now running. ID is %lu.\r\n", thread_names[thread->mThreadMode], (long unsigned) thread_getid() ) );

    // which type of object are we
    switch ( thread->mThreadMode ) {
        case kMode_Server:
            {
                /* Spawn a Server thread with these settings */
                server_spawn( thread );
            } break;
        case kMode_Client:
            {
                /* Spawn a Client thread with these settings */
                client_spawn( thread );
            } break;
        case kMode_Reporter:
            {
                /* Spawn a Reporter thread with these settings */
                reporter_spawn( thread );
            } break;
        case kMode_Listener:
            {
                // Increment the non-terminating thread count
                thread_register_nonterm();
                /* Spawn a Listener thread with these settings */
                listener_spawn( thread );
                // Decrement the non-terminating thread count
                thread_unregister_nonterm();
            } break;
        default:
            {
                FAIL(1, ( "Unknown Thread Type!\r\n" ), thread);
            } break;
    }

#ifdef HAVE_POSIX_THREAD
    // detach Thread. If someone already joined it will not do anything
    // If noone has then it will free resources upon return from this
    // function (Run_Wrapper)
    IPERF_DEBUGF( THREAD_DEBUG | IPERF_DBG_TRACE, ( "Detaching %s thread.\r\n", thread_names[thread->mThreadMode] ) );
    pthread_detach(thread->mTID);
#endif /* HAVE_POSIX_THREAD */

    // decrement thread count and send condition signal
    Condition_Lock( thread_sNum_cond );
    IPERF_DEBUGF( THREAD_DEBUG | IPERF_DBG_TRACE, ( "Decrementing thread count from %d to %d.\r\n", thread_sNum, (thread_sNum - 1) ) );
    thread_sNum--;

    IPERF_DEBUGF( CONDITION_DEBUG | IPERF_DBG_TRACE, ( "Signaling thread_sNum_cond condition.\r\n" ) );
    Condition_Signal( &thread_sNum_cond );
    Condition_Unlock( thread_sNum_cond );

    // Check if we need to start up a thread after executing this one
    if ( thread->runNext != NULL ) {
        thread_start( thread->runNext );
    }

    // Destroy this thread object
    Settings_Destroy( thread );

    return 0;
} // end thread_run_wrapper
コード例 #17
0
 void MdiEditor::PtModified()
 {
	 pyramids[layer_index]._gpu->params()=parameters[layer_index];
	 thread_start(layer_index);
 }
コード例 #18
0
ファイル: main.c プロジェクト: harish-agr/network_lib
DECLARE_TEST(udp, stream_ipv6) {
	network_address_t** address_local = 0;
	network_address_t* address = 0;

	int server_port, client_port;
	int state, iaddr, asize;
	thread_t threads[2];

	socket_t* sock_server;
	socket_t* sock_client;

	if (!network_supports_ipv6())
		return 0;

	sock_server = udp_socket_allocate();
	sock_client = udp_socket_allocate();

	address_local = network_address_local();
	for (iaddr = 0, asize = array_size(address_local); iaddr < asize; ++iaddr) {
		if (network_address_family(address_local[iaddr]) == NETWORK_ADDRESSFAMILY_IPV6) {
			address = address_local[iaddr];
			break;
		}
	}
	EXPECT_NE(address, 0);

	do {
		server_port = random32_range(1024, 35535);
		network_address_ip_set_port(address, server_port);
		if (socket_bind(sock_server, address))
			break;
	}
	while (true);

	do {
		client_port = random32_range(1024, 35535);
		network_address_ip_set_port(address, client_port);
		if (socket_bind(sock_client, address))
			break;
	}
	while (true);

	socket_set_blocking(sock_server, false);
	socket_set_blocking(sock_client, false);

	network_address_ip_set_port(address, client_port);
	socket_connect(sock_server, address, 0);

	network_address_ip_set_port(address, server_port);
	socket_connect(sock_client, address, 0);

	network_address_array_deallocate(address_local);

	state = socket_state(sock_server);
	EXPECT_TRUE(state == SOCKETSTATE_CONNECTED);

	state = socket_state(sock_client);
	EXPECT_TRUE(state == SOCKETSTATE_CONNECTED);

	socket_set_blocking(sock_server, true);
	socket_set_blocking(sock_client, true);

	thread_initialize(&threads[0], stream_blocking_thread, sock_server, STRING_CONST("io_thread"),
	                  THREAD_PRIORITY_NORMAL, 0);
	thread_initialize(&threads[1], stream_blocking_thread, sock_client, STRING_CONST("io_thread"),
	                  THREAD_PRIORITY_NORMAL, 0);

	thread_start(&threads[0]);
	thread_start(&threads[1]);

	test_wait_for_threads_startup(threads, 2);

	thread_finalize(&threads[0]);
	thread_finalize(&threads[1]);

	socket_deallocate(sock_server);
	socket_deallocate(sock_client);

	return 0;
}
コード例 #19
0
ファイル: gtkutil.c プロジェクト: mikelolasagasti/hexchat
void
gtkutil_file_req (const char *title, void *callback, void *userdata, char *filter, char *extensions,
						int flags)
{
	struct file_req *freq;
	GtkWidget *dialog;
	GtkFileFilter *filefilter;
	extern char *get_xdir_fs (void);
	char *token;
	char *tokenbuffer;

#if 0	/* native file dialogs */
#ifdef WIN32
	if (!(flags & FRF_WRITE))
	{
		freq = malloc (sizeof (struct file_req));
		freq->th = thread_new ();
		freq->flags = 0;
		freq->multiple = (flags & FRF_MULTIPLE);
		freq->callback = callback;
		freq->userdata = userdata;
		freq->title = g_locale_from_utf8 (title, -1, 0, 0, 0);
		if (!filter)
		{
			freq->filter =	"All files\0*.*\0"
							"Executables\0*.exe\0"
							"ZIP files\0*.zip\0\0";
		}
		else
		{
			freq->filter = filter;
		}

		thread_start (freq->th, win32_thread, freq);
		fe_input_add (freq->th->pipe_fd[0], FIA_FD|FIA_READ, win32_read_thread, freq);

		return;

	}
	
	else {
		freq = malloc (sizeof (struct file_req));
		freq->th = thread_new ();
		freq->flags = 0;
		freq->multiple = (flags & FRF_MULTIPLE);
		freq->callback = callback;
		freq->userdata = userdata;
		freq->title = g_locale_from_utf8 (title, -1, 0, 0, 0);
		if (!filter)
		{
			freq->filter = "All files\0*.*\0\0";
		}
		else
		{
			freq->filter = filter;
		}

		thread_start (freq->th, win32_thread2, freq);
		fe_input_add (freq->th->pipe_fd[0], FIA_FD|FIA_READ, win32_read_thread, freq);

	return;
	}
#endif
#endif

	if (flags & FRF_WRITE)
	{
		dialog = gtk_file_chooser_dialog_new (title, NULL,
												GTK_FILE_CHOOSER_ACTION_SAVE,
												GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
												GTK_STOCK_SAVE, GTK_RESPONSE_ACCEPT,
												NULL);
		if (filter && filter[0])	/* filter becomes initial name when saving */
		{
			char temp[1024];
			path_part (filter, temp, sizeof (temp));
			gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER (dialog), temp);
			gtk_file_chooser_set_current_name (GTK_FILE_CHOOSER (dialog), file_part (filter));
		}

		if (!(flags & FRF_NOASKOVERWRITE))
			gtk_file_chooser_set_do_overwrite_confirmation (GTK_FILE_CHOOSER (dialog), TRUE);
	}
	else
		dialog = gtk_file_chooser_dialog_new (title, NULL,
												GTK_FILE_CHOOSER_ACTION_OPEN,
												GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
												GTK_STOCK_OK, GTK_RESPONSE_ACCEPT,
												NULL);
	if (flags & FRF_MULTIPLE)
		gtk_file_chooser_set_select_multiple (GTK_FILE_CHOOSER (dialog), TRUE);
	if (last_dir[0])
		gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER (dialog), last_dir);
	if (flags & FRF_ADDFOLDER)
		gtk_file_chooser_add_shortcut_folder (GTK_FILE_CHOOSER (dialog),
														  get_xdir (), NULL);
	if (flags & FRF_CHOOSEFOLDER)
	{
		gtk_file_chooser_set_action (GTK_FILE_CHOOSER (dialog), GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER);
		gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER (dialog), filter);
	}
	else
	{
		if (filter && (flags & FRF_FILTERISINITIAL))
		{
			gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER (dialog), filter);
		}
		/* With DCC, we can't rely on filter as initial folder since filter already contains
		 * the filename upon DCC RECV. Thus we have no better option than to check for the message
		 * which will be the title of the window. For DCC it always contains the "offering" word.
		 * This method is really ugly but it works so we'll stick with it for now.
		 */
		else if (strstr (title, "offering") != NULL)
		{
			gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER (dialog), prefs.hex_dcc_dir);
		}
		/* by default, open the config folder */
		else
		{
			gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER (dialog), get_xdir ());
		}
	}

	if (flags & FRF_EXTENSIONS && extensions != NULL)
	{
		filefilter = gtk_file_filter_new ();
		tokenbuffer = g_strdup (extensions);
		token = strtok (tokenbuffer, ";");

		while (token != NULL)
		{
			gtk_file_filter_add_pattern (filefilter, token);
			token = strtok (NULL, ";");
		}

		g_free (tokenbuffer);
		gtk_file_chooser_set_filter (GTK_FILE_CHOOSER (dialog), filefilter);
	}

	freq = malloc (sizeof (struct file_req));
	freq->dialog = dialog;
	freq->flags = flags;
	freq->callback = callback;
	freq->userdata = userdata;

	g_signal_connect (G_OBJECT (dialog), "response",
							G_CALLBACK (gtkutil_file_req_response), freq);
	g_signal_connect (G_OBJECT (dialog), "destroy",
						   G_CALLBACK (gtkutil_file_req_destroy), (gpointer) freq);
	gtk_widget_show (dialog);
}
コード例 #20
0
ファイル: main.c プロジェクト: harish-agr/network_lib
DECLARE_TEST(udp, datagram_ipv6) {
	network_address_t** address_local = 0;
	network_address_t* address = 0;
	network_address_t* address_server = 0;
	test_datagram_arg_t client_arg[4];

	int server_port;
	int state, iaddr, asize;
	thread_t threads[5];

	socket_t* sock_server;
	socket_t* sock_client[4];

	if (!network_supports_ipv6())
		return 0;

	sock_server = udp_socket_allocate();
	sock_client[0] = udp_socket_allocate();
	sock_client[1] = udp_socket_allocate();
	sock_client[2] = udp_socket_allocate();
	sock_client[3] = udp_socket_allocate();

	address_local = network_address_local();
	for (iaddr = 0, asize = array_size(address_local); iaddr < asize; ++iaddr) {
		if (network_address_family(address_local[iaddr]) == NETWORK_ADDRESSFAMILY_IPV6) {
			address = address_local[iaddr];
			break;
		}
	}
	EXPECT_NE(address, 0);

	do {
		server_port = random32_range(1024, 35535);
		network_address_ip_set_port(address, server_port);
		if (socket_bind(sock_server, address))
			break;
	}
	while (true);

	address_server = network_address_clone(address);
	network_address_ip_set_port(address_server, server_port);

	network_address_array_deallocate(address_local);

	state = socket_state(sock_server);
	EXPECT_TRUE(state == SOCKETSTATE_NOTCONNECTED);

	state = socket_state(sock_client[0]);
	EXPECT_TRUE(state == SOCKETSTATE_NOTCONNECTED);

	state = socket_state(sock_client[1]);
	EXPECT_TRUE(state == SOCKETSTATE_NOTCONNECTED);

	state = socket_state(sock_client[2]);
	EXPECT_TRUE(state == SOCKETSTATE_NOTCONNECTED);

	state = socket_state(sock_client[3]);
	EXPECT_TRUE(state == SOCKETSTATE_NOTCONNECTED);

	socket_set_blocking(sock_server, true);
	socket_set_blocking(sock_client[0], true);
	socket_set_blocking(sock_client[1], true);
	socket_set_blocking(sock_client[2], true);
	socket_set_blocking(sock_client[3], true);

	client_arg[0].sock = sock_client[0]; client_arg[0].target = address_server;
	client_arg[1].sock = sock_client[1]; client_arg[1].target = address_server;
	client_arg[2].sock = sock_client[2]; client_arg[2].target = address_server;
	client_arg[3].sock = sock_client[3]; client_arg[3].target = address_server;

	thread_initialize(&threads[0], datagram_server_blocking_thread, sock_server,
	                  STRING_CONST("server_thread"), THREAD_PRIORITY_NORMAL, 0);
	thread_initialize(&threads[1], datagram_client_blocking_thread, &client_arg[0],
	                  STRING_CONST("client_thread"), THREAD_PRIORITY_NORMAL, 0);
	thread_initialize(&threads[2], datagram_client_blocking_thread, &client_arg[1],
	                  STRING_CONST("client_thread"), THREAD_PRIORITY_NORMAL, 0);
	thread_initialize(&threads[3], datagram_client_blocking_thread, &client_arg[2],
	                  STRING_CONST("client_thread"), THREAD_PRIORITY_NORMAL, 0);
	thread_initialize(&threads[4], datagram_client_blocking_thread, &client_arg[3],
	                  STRING_CONST("client_thread"), THREAD_PRIORITY_NORMAL, 0);

	thread_start(&threads[0]);
	thread_start(&threads[1]);
	thread_start(&threads[2]);
	thread_start(&threads[3]);
	thread_start(&threads[4]);

	test_wait_for_threads_startup(threads, 5);

	thread_finalize(&threads[0]);
	thread_finalize(&threads[1]);
	thread_finalize(&threads[2]);
	thread_finalize(&threads[3]);
	thread_finalize(&threads[4]);

	socket_deallocate(sock_server);
	socket_deallocate(sock_client[0]);
	socket_deallocate(sock_client[1]);
	socket_deallocate(sock_client[2]);
	socket_deallocate(sock_client[3]);

	memory_deallocate(address_server);

	return 0;
}
コード例 #21
0
ファイル: gtkutil.c プロジェクト: cremno/hexchat
void
gtkutil_file_req (const char *title, void *callback, void *userdata, char *filter,
						int flags)
{
	struct file_req *freq;
	GtkWidget *dialog;
	extern char *get_xdir_fs (void);

#ifdef WIN32
	if (!(flags & FRF_WRITE))
	{
		freq = malloc (sizeof (struct file_req));
		freq->th = thread_new ();
		freq->flags = 0;
		freq->multiple = (flags & FRF_MULTIPLE);
		freq->callback = callback;
		freq->userdata = userdata;
		freq->title = g_locale_from_utf8 (title, -1, 0, 0, 0);
		if (!filter)
		{
			freq->filter =	"All files\0*.*\0"
							"Executables\0*.exe\0"
							"ZIP files\0*.zip\0\0";
		}
		else
		{
			freq->filter = filter;
		}

		thread_start (freq->th, win32_thread, freq);
		fe_input_add (freq->th->pipe_fd[0], FIA_FD|FIA_READ, win32_read_thread, freq);

		return;

	}
	
	else {
		freq = malloc (sizeof (struct file_req));
		freq->th = thread_new ();
		freq->flags = 0;
		freq->multiple = (flags & FRF_MULTIPLE);
		freq->callback = callback;
		freq->userdata = userdata;
		freq->title = g_locale_from_utf8 (title, -1, 0, 0, 0);
		if (!filter)
		{
			freq->filter = "All files\0*.*\0\0";
		}
		else
		{
			freq->filter = filter;
		}

		thread_start (freq->th, win32_thread2, freq);
		fe_input_add (freq->th->pipe_fd[0], FIA_FD|FIA_READ, win32_read_thread, freq);

	return;
	}
#endif

	if (flags & FRF_WRITE)
	{
		dialog = gtk_file_chooser_dialog_new (title, NULL,
												GTK_FILE_CHOOSER_ACTION_SAVE,
												GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
												GTK_STOCK_SAVE, GTK_RESPONSE_ACCEPT,
												NULL);
		if (filter && filter[0])	/* filter becomes initial name when saving */
		{
			char temp[1024];
			path_part (filter, temp, sizeof (temp));
			gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER (dialog), temp);
			gtk_file_chooser_set_current_name (GTK_FILE_CHOOSER (dialog), file_part (filter));
		}

		if (!(flags & FRF_NOASKOVERWRITE))
			gtk_file_chooser_set_do_overwrite_confirmation (GTK_FILE_CHOOSER (dialog), TRUE);
	}
	else
		dialog = gtk_file_chooser_dialog_new (title, NULL,
												GTK_FILE_CHOOSER_ACTION_OPEN,
												GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
												GTK_STOCK_OK, GTK_RESPONSE_ACCEPT,
												NULL);
	if (flags & FRF_MULTIPLE)
		gtk_file_chooser_set_select_multiple (GTK_FILE_CHOOSER (dialog), TRUE);
	if (last_dir[0])
		gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER (dialog), last_dir);
	if (flags & FRF_ADDFOLDER)
		gtk_file_chooser_add_shortcut_folder (GTK_FILE_CHOOSER (dialog),
														  get_xdir_fs (), NULL);
	if (flags & FRF_CHOOSEFOLDER)
	{
		gtk_file_chooser_set_action (GTK_FILE_CHOOSER (dialog), GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER);
		gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER (dialog), filter);
	}
	else
	{
		if (filter && (flags & FRF_FILTERISINITIAL))
			gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER (dialog), filter);
	}

	freq = malloc (sizeof (struct file_req));
	freq->dialog = dialog;
	freq->flags = flags;
	freq->callback = callback;
	freq->userdata = userdata;

	g_signal_connect (G_OBJECT (dialog), "response",
							G_CALLBACK (gtkutil_file_req_response), freq);
	g_signal_connect (G_OBJECT (dialog), "destroy",
						   G_CALLBACK (gtkutil_file_req_destroy), (gpointer) freq);
	gtk_widget_show (dialog);
}
コード例 #22
0
ファイル: Thread.c プロジェクト: rocksclusters-attic/hpc
DWORD WINAPI
#else
void*
#endif
thread_run_wrapper( void* paramPtr ) {
    struct thread_Settings* thread = (struct thread_Settings*) paramPtr;

    // which type of object are we
    switch ( thread->mThreadMode ) {
        case kMode_Server:
            {
                /* Spawn a Server thread with these settings */
                server_spawn( thread );
            } break;
        case kMode_Client:
            {
                /* Spawn a Client thread with these settings */
                client_spawn( thread );
            } break;
        case kMode_Reporter:
            {
                /* Spawn a Reporter thread with these settings */
                reporter_spawn( thread );
            } break;
        case kMode_Listener:
            {
                // Increment the non-terminating thread count
                thread_register_nonterm();
                /* Spawn a Listener thread with these settings */
                listener_spawn( thread );
                // Decrement the non-terminating thread count
                thread_unregister_nonterm();
            } break;
        default:
            {
                FAIL(1, "Unknown Thread Type!\n", thread);
            } break;
    }

#ifdef HAVE_POSIX_THREAD
    // detach Thread. If someone already joined it will not do anything
    // If noone has then it will free resources upon return from this
    // function (Run_Wrapper)
    pthread_detach(thread->mTID);
#endif

    // decrement thread count and send condition signal
    Condition_Lock( thread_sNum_cond );
    thread_sNum--;
    Condition_Signal( &thread_sNum_cond );
    Condition_Unlock( thread_sNum_cond );

    // Check if we need to start up a thread after executing this one
    if ( thread->runNext != NULL ) {
        thread_start( thread->runNext );
    }

    // Destroy this thread object
    Settings_Destroy( thread );

    return 0;
} // end run_wrapper
コード例 #23
0
ファイル: labyrinth.c プロジェクト: jaingaurav/rstm
/* =============================================================================
 * main
 * =============================================================================
 */
MAIN(argc, argv)
{
    /*
     * Initialization
     */
    parseArgs(argc, (char** const)argv);
    long numThread = global_params[PARAM_THREAD];
    SIM_GET_NUM_CPU(numThread);
    TM_STARTUP(numThread);
    P_MEMORY_STARTUP(numThread);
    thread_startup(numThread);
    maze_t* mazePtr = maze_alloc();
    assert(mazePtr);
    long numPathToRoute = maze_read(mazePtr, global_inputFile);
    router_t* routerPtr = router_alloc(global_params[PARAM_XCOST],
                                       global_params[PARAM_YCOST],
                                       global_params[PARAM_ZCOST],
                                       global_params[PARAM_BENDCOST]);
    assert(routerPtr);
    list_t* pathVectorListPtr = list_alloc(NULL);
    assert(pathVectorListPtr);

    /*
     * Run transactions
     */
    router_solve_arg_t routerArg = {routerPtr, mazePtr, pathVectorListPtr};
    // NB: Since ASF/PTLSim "REAL" is native execution, and since we are using
    //     wallclock time, we want to be sure we read time inside the
    //     simulator, or else we report native cycles spent on the benchmark
    //     instead of simulator cycles.
    GOTO_SIM();
    TIMER_T startTime;
    TIMER_READ(startTime);
#ifdef OTM
#pragma omp parallel
    {
        router_solve((void *)&routerArg);
    }
#else
    thread_start(router_solve, (void*)&routerArg);
#endif
    TIMER_T stopTime;
    TIMER_READ(stopTime);
    // NB: As above, timer reads must be done inside of the simulated region
    //     for PTLSim/ASF
    GOTO_REAL();

    long numPathRouted = 0;
    list_iter_t it;
    list_iter_reset(&it, pathVectorListPtr);
    while (list_iter_hasNext(&it, pathVectorListPtr)) {
        vector_t* pathVectorPtr = (vector_t*)list_iter_next(&it, pathVectorListPtr);
        numPathRouted += vector_getSize(pathVectorPtr);
    }
    printf("Paths routed    = %li\n", numPathRouted);
    printf("Elapsed time    = %f seconds\n", TIMER_DIFF_SECONDS(startTime, stopTime));

    /*
     * Check solution and clean up
     */
    assert(numPathRouted <= numPathToRoute);
    bool status = maze_checkPaths(mazePtr, pathVectorListPtr, global_doPrint);
    assert(status);
    puts("Verification passed.");
    maze_free(mazePtr);
    router_free(routerPtr);

    TM_SHUTDOWN();
    P_MEMORY_SHUTDOWN();

    thread_shutdown();


    MAIN_RETURN(0);
}
コード例 #24
0
ファイル: genome.c プロジェクト: takayuki/al
/* =============================================================================
 * main
 * =============================================================================
 */
MAIN (argc,argv)
{
    TIMER_T start;
    TIMER_T stop;

    GOTO_REAL();

    /* Initialization */
    parseArgs(argc, (char** const)argv);
    SIM_GET_NUM_CPU(global_params[PARAM_THREAD]);

    printf("Creating gene and segments... ");
    fflush(stdout);

    long geneLength = global_params[PARAM_GENE];
    long segmentLength = global_params[PARAM_SEGMENT];
    long minNumSegment = global_params[PARAM_NUMBER];
    long numThread = global_params[PARAM_THREAD];

    TM_STARTUP(numThread);
    P_MEMORY_STARTUP(numThread);

    random_t* randomPtr = random_alloc();
    assert(randomPtr != NULL);
    random_seed(randomPtr, 0);

    gene_t* genePtr = gene_alloc(geneLength);
    assert( genePtr != NULL);
    gene_create(genePtr, randomPtr);
    char* gene = genePtr->contents;

    segments_t* segmentsPtr = segments_alloc(segmentLength, minNumSegment);
    assert(segmentsPtr != NULL);
    segments_create(segmentsPtr, genePtr, randomPtr);
    sequencer_t* sequencerPtr = sequencer_alloc(geneLength, segmentLength, segmentsPtr);
    assert(sequencerPtr != NULL);

    puts("done.");
    printf("Gene length     = %li\n", genePtr->length);
    printf("Segment length  = %li\n", segmentsPtr->length);
    printf("Number segments = %li\n", vector_getSize(segmentsPtr->contentsPtr));
    fflush(stdout);

    /* Benchmark */
    printf("Sequencing gene... ");
    fflush(stdout);
    TIMER_READ(start);
    GOTO_SIM();
    thread_startup(numThread, sequencer_run, (void*)sequencerPtr);
    thread_start();
    GOTO_REAL();
    TIMER_READ(stop);
    puts("done.");
    printf("Time = %lf\n", TIMER_DIFF_SECONDS(start, stop));
    fflush(stdout);

    /* Check result */
    {
        char* sequence = sequencerPtr->sequence;
        int result = strcmp(gene, sequence);
        printf("Sequence matches gene: %s\n", (result ? "no" : "yes"));
        if (result) {
            printf("gene     = %s\n", gene);
            printf("sequence = %s\n", sequence);
        }
        fflush(stdout);
        assert(strlen(sequence) >= strlen(gene));
    }

    /* Clean up */
    printf("Deallocating memory... ");
    fflush(stdout);
    sequencer_free(sequencerPtr);
    segments_free(segmentsPtr);
    gene_free(genePtr);
    random_free(randomPtr);
    puts("done.");
    fflush(stdout);

    al_dump(&sequencerLock);

    TM_SHUTDOWN();
    P_MEMORY_SHUTDOWN();

    GOTO_SIM();

    thread_shutdown();

    MAIN_RETURN(0);
}
コード例 #25
0
CompileThreadBlock::CompileThreadBlock(EditableMap *wmap, unsigned char **lightmap)
    : CompileThread(wmap, lightmap)
{
    thread_start();
}
コード例 #26
0
ファイル: main.c プロジェクト: rampantpixels/foundation_lib
DECLARE_TEST(profile, stream) {
	thread_t thread[32];
	int ith;
	uint64_t frame;
	string_t filename;

	error(); //Clear error

	filename = path_allocate_concat(STRING_ARGS(environment_temporary_directory()),
	                                STRING_CONST("test.profile"));
	//log_infof(HASH_TEST, STRING_CONST("Output to profile file: %.*s"), STRING_FORMAT(filename));
	fs_make_directory(STRING_ARGS(environment_temporary_directory()));
	_profile_stream = fs_open_file(STRING_ARGS(filename), STREAM_OUT | STREAM_BINARY);
	string_deallocate(filename.str);

	profile_initialize(STRING_CONST("test_profile"), _test_profile_buffer, TEST_PROFILE_BUFFER_SIZE);
	profile_set_output(_profile_file_writer);
	profile_set_output_wait(10);
	profile_enable(true);

	for (ith = 0; ith < 32; ++ith)
		thread_initialize(&thread[ith], _profile_stream_thread, 0, STRING_CONST("profile_thread"),
		                  THREAD_PRIORITY_NORMAL, 0);
	for (ith = 0; ith < 32; ++ith)
		thread_start(&thread[ith]);

	test_wait_for_threads_startup(thread, 32);

	for (frame = 0; frame < 1000; ++frame) {
		thread_sleep(16);
		profile_log(
		    STRING_CONST("This is a really long profile log line that should break into multiple profile blocks automatically without causing any issues whatsoever if everything works as expected which it should or the code needs to be fixed"));
		profile_end_frame(frame++);
		if ((frame % 30) == 0) {
			profile_enable(false);
			thread_sleep(10);
			profile_enable(true);
		}
	}

	for (ith = 0; ith < 32; ++ith)
		thread_signal(&thread[ith]);

	test_wait_for_threads_finish(thread, 32);

	for (ith = 0; ith < 32; ++ith)
		thread_finalize(&thread[ith]);

	profile_end_frame(frame++);
	profile_set_output_wait(10000);

	thread_sleep(1000);

	profile_begin_block(STRING_CONST("Should be cleaned up"));
	profile_end_block();

	profile_enable(false);
	profile_finalize();

	error();

	stream_deallocate(_profile_stream);

//TODO: Validate that output is sane
	log_debugf(HASH_TEST, STRING_CONST("Generated %" PRId64 " blocks"),
	           atomic_load64(&_profile_generated_blocks));

	return 0;
}
コード例 #27
0
ファイル: main.c プロジェクト: emoon/foundation_lib
DECLARE_TEST( profile, stream )
{
	object_t thread[32];
	int ith;
	int frame;
	char* filename;

	error();

	filename = path_merge( environment_temporary_directory(), "test.profile" );
	log_infof( HASH_TEST, "Output to profile file: %s", filename );
	fs_make_directory( environment_temporary_directory() );
	_profile_stream = fs_open_file( filename, STREAM_OUT | STREAM_BINARY );
	string_deallocate( filename );

	profile_initialize( "test_profile", _test_profile_buffer, _test_profile_buffer_size );
	profile_set_output( _profile_file_writer );
	profile_set_output_wait( 10 );
	profile_enable( true );

	for( ith = 0; ith < 32; ++ith )
	{
		thread[ith] = thread_create( _profile_stream_thread, "profile_thread", THREAD_PRIORITY_NORMAL, 0 );
		thread_start( thread[ith], 0 );
	}

	test_wait_for_threads_startup( thread, 32 );

	for( frame = 0; frame < 1000; ++frame )
	{
		thread_sleep( 16 );
		profile_log( "This is a really long profile log line that should break into multiple profile blocks automatically without causing any issues whatsoever if everything works as expected which it should or the code needs to be fixed" );
		profile_end_frame( frame++ );
		if( ( frame % 30 ) == 0 )
		{
			profile_enable( false );
			thread_sleep( 10 );
			profile_enable( true );
		}
	}

	for( ith = 0; ith < 32; ++ith )
	{
		thread_terminate( thread[ith] );
		thread_destroy( thread[ith] );
		thread_yield();
	}

	test_wait_for_threads_exit( thread, 32 );

	profile_end_frame( frame++ );
	profile_set_output_wait( 100 );

	thread_sleep( 1000 );

	profile_enable( false );
	profile_shutdown();

	error();

	stream_deallocate( _profile_stream );

	//TODO: Validate that output is sane
	log_debugf( HASH_TEST, "Generated %lld blocks", atomic_load64( &_profile_generated_blocks ) );

	return 0;
}
コード例 #28
0
/* =============================================================================
 * main
 * =============================================================================
 */
MAIN(argc, argv)
{
    char exitmsg[1024];

    GOTO_REAL();

    load_syncchar_map("sync_char.map.yada");

    /*
     * Initialization
     */

    parseArgs(argc, (char** const)argv);
    sprintf(exitmsg, "END BENCHMARK %s-parallel-phase\n", argv[0]);

    SIM_GET_NUM_CPU(global_numThread);
    TM_STARTUP(global_numThread);
    P_MEMORY_STARTUP(global_numThread);
    thread_startup(global_numThread);
    global_meshPtr = mesh_alloc();
    assert(global_meshPtr);
    printf("Angle constraint = %lf\n", global_angleConstraint);
    printf("Reading input... ");
    long initNumElement = mesh_read(global_meshPtr, global_inputPrefix);
    puts("done.");
    global_workHeapPtr = heap_alloc(1, &element_heapCompare);
    assert(global_workHeapPtr);
    long initNumBadElement = initializeWork(global_workHeapPtr, global_meshPtr);

    printf("Initial number of mesh elements = %li\n", initNumElement);
    printf("Initial number of bad elements  = %li\n", initNumBadElement);
    printf("Starting triangulation...");
    fflush(stdout);

    /*
     * Run benchmark
     */

    TIMER_T start;
    TIMER_READ(start);
    OSA_PRINT("entering parallel phase\n",0);
    START_INSTRUMENTATION();
    GOTO_SIM();
#ifdef OTM
#pragma omp parallel
    {
        process();
    }
#else
    thread_start(process, NULL);
#endif
    GOTO_REAL();
    OSA_PRINT("exiting parallel phase\n",0);
    OSA_PRINT(exitmsg,0);
    STOP_INSTRUMENTATION();
    TIMER_T stop;
    TIMER_READ(stop)

    puts(" done.");
    printf("Elapsed time                    = %0.3lf\n",
           TIMER_DIFF_SECONDS(start, stop));
    fflush(stdout);

    /*
     * Check solution
     */

    long finalNumElement = initNumElement + global_totalNumAdded;
    printf("Final mesh size                 = %li\n", finalNumElement);
    printf("Number of elements processed    = %li\n", global_numProcess);
    fflush(stdout);

#if 0
    bool_t isSuccess = mesh_check(global_meshPtr, finalNumElement);
#else
    bool_t isSuccess = TRUE;
#endif
    printf("Final mesh is %s\n", (isSuccess ? "valid." : "INVALID!"));
    fflush(stdout);
    assert(isSuccess);

    /*
     * TODO: deallocate mesh and work heap
     */

    TM_SHUTDOWN();
    P_MEMORY_SHUTDOWN();

    GOTO_SIM();

    thread_shutdown();

    MAIN_RETURN(0);
}
コード例 #29
0
ファイル: main.c プロジェクト: milzod/foundation_lib
int main_run( void* main_arg )
{
#if !BUILD_MONOLITHIC
	const char* pattern = 0;
	char** exe_paths = 0;
	unsigned int iexe, exesize;
	process_t* process = 0;
	char* process_path = 0;
	unsigned int* exe_flags = 0;
#endif
#if FOUNDATION_PLATFORM_IOS || FOUNDATION_PLATFORM_ANDROID || FOUNDATION_PLATFORM_PNACL
	int remain_counter = 0;
#endif
#if BUILD_DEBUG
	const char* build_name = "debug";
#elif BUILD_RELEASE
	const char* build_name = "release";
#elif BUILD_PROFILE
	const char* build_name = "profile";
#elif BUILD_DEPLOY
	const char* build_name = "deploy";
#endif
	int process_result = 0;
	object_t thread = 0;
	FOUNDATION_UNUSED( main_arg );
	FOUNDATION_UNUSED( build_name );

	log_set_suppress( HASH_TEST, ERRORLEVEL_DEBUG );

	log_infof( HASH_TEST, "Foundation library v%s built for %s using %s (%s)", string_from_version_static( foundation_version() ), FOUNDATION_PLATFORM_DESCRIPTION, FOUNDATION_COMPILER_DESCRIPTION, build_name );

	thread = thread_create( event_thread, "event_thread", THREAD_PRIORITY_NORMAL, 0 );
	thread_start( thread, 0 );
	while( !thread_is_running( thread ) )
		thread_sleep( 10 );

#if FOUNDATION_PLATFORM_IOS || FOUNDATION_PLATFORM_ANDROID
	while( !_test_should_start )
	{
#if FOUNDATION_PLATFORM_ANDROID
		system_process_events();
#endif
		thread_sleep( 100 );
	}
#endif

	fs_remove_directory( environment_temporary_directory() );

#if BUILD_MONOLITHIC

	test_run_fn tests[] = {
		test_app_run,
		test_array_run,
		test_atomic_run,
		test_base64_run,
		test_bitbuffer_run,
		test_blowfish_run,
		test_bufferstream_run,
		test_config_run,
		test_crash_run,
		test_environment_run,
		test_error_run,
		test_event_run,
		test_fs_run,
		test_hash_run,
		test_hashmap_run,
		test_hashtable_run,
		test_library_run,
		test_math_run,
		test_md5_run,
		test_mutex_run,
		test_objectmap_run,
		test_path_run,
		test_pipe_run,
		test_process_run,
		test_profile_run,
		test_radixsort_run,
		test_random_run,
		test_regex_run,
		test_ringbuffer_run,
		test_semaphore_run,
		test_stacktrace_run,
		test_stream_run, //stream test closes stdin
		test_string_run,
		test_system_run,
		test_time_run,
		test_uuid_run,
		0
	};

#if FOUNDATION_PLATFORM_ANDROID

	object_t test_thread = thread_create( test_runner, "test_runner", THREAD_PRIORITY_NORMAL, 0 );
	thread_start( test_thread, tests );

	log_debug( HASH_TEST, "Starting test runner thread" );

	while( !thread_is_running( test_thread ) )
	{
		system_process_events();
		thread_sleep( 10 );
	}

	while( thread_is_running( test_thread ) )
	{
		system_process_events();
		thread_sleep( 10 );
	}

	process_result = (int)(intptr_t)thread_result( test_thread );
	thread_destroy( test_thread );

	while( thread_is_thread( test_thread ) )
	{
		system_process_events();
		thread_sleep( 10 );
	}

#else

	process_result = (int)(intptr_t)test_runner( 0, tests );

#endif

	if( process_result != 0 )
		log_warnf( HASH_TEST, WARNING_SUSPICIOUS, "Tests failed with exit code %d", process_result );

#if FOUNDATION_PLATFORM_IOS || FOUNDATION_PLATFORM_ANDROID || FOUNDATION_PLATFORM_PNACL

	while( !_test_should_terminate && _test_have_focus && ( remain_counter < 50 ) )
	{
		system_process_events();
		thread_sleep( 100 );
		++remain_counter;
	}

#endif

	log_debug( HASH_TEST, "Exiting main loop" );

#else // !BUILD_MONOLITHIC

	//Find all test executables in the current executable directory
#if FOUNDATION_PLATFORM_WINDOWS
	pattern = "^test-.*\\.exe$";
#elif FOUNDATION_PLATFORM_MACOSX
	pattern = "^test-.*$";
#elif FOUNDATION_PLATFORM_POSIX
	pattern = "^test-.*$";
#else
#  error Not implemented
#endif
	exe_paths = fs_matching_files( environment_executable_directory(), pattern, false );
	array_resize( exe_flags, array_size( exe_paths ) );
	memset( exe_flags, 0, sizeof( unsigned int ) * array_size( exe_flags ) );
#if FOUNDATION_PLATFORM_MACOSX
	//Also search for test applications
	const char* app_pattern = "^test-.*\\.app$";
	regex_t* app_regex = regex_compile( app_pattern );
	char** subdirs = fs_subdirs( environment_executable_directory() );
	for( int idir = 0, dirsize = array_size( subdirs ); idir < dirsize; ++idir )
	{
		if( regex_match( app_regex, subdirs[idir], string_length( subdirs[idir] ), 0, 0 ) )
		{
			array_push( exe_paths, string_substr( subdirs[idir], 0, string_length( subdirs[idir] ) - 4 ) );
			array_push( exe_flags, PROCESS_MACOSX_USE_OPENAPPLICATION );
		}
	}
	string_array_deallocate( subdirs );
	regex_deallocate( app_regex );
#endif
	for( iexe = 0, exesize = array_size( exe_paths ); iexe < exesize; ++iexe )
	{
		bool is_self = false;
		char* exe_file_name = path_base_file_name( exe_paths[iexe] );
		if( string_equal( exe_file_name, environment_executable_name() ) )
			is_self = true;
		string_deallocate( exe_file_name );
		if( is_self )
			continue; //Don't run self

		process_path = path_merge( environment_executable_directory(), exe_paths[iexe] );

		process = process_allocate();

		process_set_executable_path( process, process_path );
		process_set_working_directory( process, environment_executable_directory() );
		process_set_flags( process, PROCESS_ATTACHED | exe_flags[iexe] );

		log_infof( HASH_TEST, "Running test executable: %s", exe_paths[iexe] );

		process_result = process_spawn( process );
		while( process_result == PROCESS_WAIT_INTERRUPTED )
		{
			thread_sleep( 10 );
			process_result = process_wait( process );
		}
		process_deallocate( process );

		string_deallocate( process_path );

		if( process_result != 0 )
		{
			if( process_result >= PROCESS_INVALID_ARGS )
				log_warnf( HASH_TEST, WARNING_SUSPICIOUS, "Tests failed, process terminated with error %x", process_result );
			else
				log_warnf( HASH_TEST, WARNING_SUSPICIOUS, "Tests failed with exit code %d", process_result );
			process_set_exit_code( -1 );
			goto exit;
		}

		log_infof( HASH_TEST, "All tests from %s passed (%d)", exe_paths[iexe], process_result );
	}

	log_info( HASH_TEST, "All tests passed" );

exit:

	if( exe_paths )
		string_array_deallocate( exe_paths );
	array_deallocate( exe_flags );

#endif

	thread_terminate( thread );
	thread_destroy( thread );
	while( thread_is_running( thread ) )
		thread_sleep( 10 );
	while( thread_is_thread( thread ) )
		thread_sleep( 10 );

	log_infof( HASH_TEST, "Tests exiting: %d", process_result );

	return process_result;
}
コード例 #30
0
ファイル: sorter-main.c プロジェクト: NHHSBotball/Botball2013
int main(int argc, char** argv) {
    enable_servo(kServoPortSorter);
    set_servo_position(kServoPortSorter, kServoPositionSorterCenter);
    clear_motor_position_counter(kMotorPortBayLeft);
    clear_motor_position_counter(kMotorPortBayRight);
    create_connect();
    camera_open(LOW_RES);
    
    scanf("%s", NULL);
    printf("waiting for light\n");
    while (analog(0) > 200) {}
    
    shut_down_in(700000);
    
    motor(kMotorPortBayLeft, 10);
    motor(kMotorPortBayRight, 10);
    while (get_motor_position_counter(kMotorPortBayLeft) < 230 || get_motor_position_counter(kMotorPortBayRight) < 230) {
        printf("pos: %i/%i\n", get_motor_position_counter(kMotorPortBayLeft), get_motor_position_counter(kMotorPortBayRight));
    }
    motor(kMotorPortBayLeft, 0);
    motor(kMotorPortBayLeft, 0);
    // wait_for_side_button();
    
    msleep(6000);
    
    create_drive_straight(200);
    msleep(1850);
    create_spin_CCW(200);
    msleep(750);
    create_drive_straight(-200);
    msleep(1500);
    create_spin_CW(200);
    msleep(1750);
    create_drive_straight(200);
    while (!get_create_lbump() && !get_create_rbump()) {}
    create_drive_straight(-150);
    msleep(900);
    create_spin_CCW(200);
    msleep(950);
    create_drive_straight(150);
    while (!get_create_lbump() && !get_create_rbump()) {}
    create_stop();
    
    msleep(10000);
    
    thread all_off = thread_create(wait_for_kill);
    thread_start(all_off);
    
    raise_bay();
    create_spin_CW(100);
    msleep(500);
    create_drive_straight(-100);
    msleep(1000);
    create_stop();
    
    thread jiggle_c = thread_create(jiggle_create);
    thread_start(jiggle_c);
    thread sort_b = thread_create(sort_balls);
    thread_start(sort_b);
    
    msleep(33000);
    
    while (true) {}
    
    /*thread_destroy(jiggle_c);
    create_stop();
    lower_bay();
    create_drive_straight(100);
    while (!get_create_lbump() && !get_create_rbump()) {}
    create_stop();
    
    msleep(10000);
    
    raise_bay();
    create_spin_CW(100);
    msleep(500);
    create_drive_straight(-100);
    msleep(1000);
    create_stop();
    
    thread_create(jiggle_create);
    thread_start(jiggle_c);
    thread_create(sort_balls);
    
    while (true) {}
    
    camera_close();*/
    return 0;
}