Ejemplo n.º 1
0
void OSystem_3DS::destroyEvents() {
	threadJoin(_timerThread, U64_MAX);
	threadFree(_timerThread);

	threadJoin(_eventThread, U64_MAX);
	threadFree(_eventThread);
	delete eventMutex;
}
Ejemplo n.º 2
0
 bool SocketServer::StopListening()
 {
   shutdown_ = true;
   CloseSocket();
   threadJoin(server_thread_);
   return true;
 }
Ejemplo n.º 3
0
void workerPoolJoin() {
	assert(M != NULL);
	int i;
	for (i=0; i < M->threadNum; i++) {
		threadJoin(M->threads[i]);	
	}
}
int main(void)
{
	int id1, id2;
	int p1;
	int p2;

	p1 = 23;
	p2 = 2;

	int *result1, *result2;

	//initialize the threading library. DON'T call this more than once!
	threadInit();

	//always start the timer after threadInit
	set_timer();

	id1 = threadCreate(/*some func*/,(void*)&p1);
	printf("created thread 1.\n");	
	
	id2 = threadCreate(/*some func*/,(void*)&p2);
	printf("created thread 2.\n");

	threadJoin(id1, (void*)&result1);
	printf("joined #1 --> %d.\n",*result1);

}
Ejemplo n.º 5
0
void gspExitEventHandler(void)
{
	// Stop event thread
	gspRunEvents = false;
	svcSignalEvent(gspEvent);
	threadJoin(gspEventThread, U64_MAX);
}
Ejemplo n.º 6
0
void OSystem_3DS::destroyAudio() {
	if (hasAudio) {
		threadJoin(audioThread, U64_MAX);
		threadFree(audioThread);
		ndspExit();
	}

	delete _mixer;
	_mixer = 0;
}
Ejemplo n.º 7
0
void aptExit(void)
{
	if (AtomicDecrement(&aptRefCount)) return;

	if(!aptIsCrippled())aptAppletUtility_Exit_RetToApp(0);

	// This is only executed when application-termination was triggered via the home-menu power-off screen.
	if(aptGetStatusPower() == 1)
	{
		aptOpenSession();
		APT_ReplySleepQuery(currentAppId, 0x0);
		aptCloseSession();
	}

	if(!aptIsCrippled())
	{
		bool isReinit = aptIsReinit();
		if (aptGetStatus() == APP_EXITING || !isReinit)
		{
			aptOpenSession();
			APT_PrepareToCloseApplication(0x1);
			aptCloseSession();
		
			aptOpenSession();
			APT_CloseApplication(0x0, 0x0, 0x0);
			aptCloseSession();

			if (isReinit)
			{
				extern void (*__system_retAddr)(void);
				__system_retAddr = NULL;
			}
		} else if (isReinit)
		{
			aptOpenSession();
			APT_Finalize(currentAppId);
			aptCloseSession();
		}
	}

	svcSignalEvent(aptEvents[2]);
	threadJoin(aptEventHandlerThread, U64_MAX);
	svcCloseHandle(aptEvents[2]);
	
	svcCloseHandle(aptSleepSync);

	svcCloseHandle(aptLockHandle);
	svcCloseHandle(aptStatusEvent);
}
Ejemplo n.º 8
0
extern void threadPoolTerminate() {

    if (threadPool == NULL) {
        return;
    }

    int i;
    ThreadPoolQueue* queue = &(threadPool->queue);
    
    semaphoreWait(&(queue->mutex));
    
    threadPool->terminated = 1;

    // unlock all threads
    for (i = 0; i < threadPool->threadsLen; ++i) {
        semaphorePost(&(queue->submit));
    }

    // unlock waiting on full queue
    semaphorePost(&(queue->wait)); 
    
    semaphorePost(&(queue->mutex));
    
    // wait for threads to be killed
    for (i = 0; i < threadPool->threadsLen; ++i) {
        threadJoin(threadPool->threads[i]);
    }
    
    // release all waiting on tasks
    for (i = queue->current; i != queue->last; ++i) {
        if (i == queue->maxLength) i = 0;
        semaphorePost(&(queue->data[i]->wait));
    }
    
    semaphoreDelete(&(queue->wait));
    semaphoreDelete(&(queue->submit));
    semaphoreDelete(&(queue->mutex));

    free(queue->data);
    free(threadPool->threads);
        
    free(threadPool);
    threadPool = NULL;
}
Ejemplo n.º 9
0
/**
 * Test that we can write a file with libhdfs and then read it back
 */
int main(void)
{
    int i, tlhNumThreads;
    const char *tlhNumThreadsStr;
    struct tlhThreadInfo ti[TLH_MAX_THREADS];
    struct NativeMiniDfsConf conf = {
        1, /* doFormat */
    };

    tlhNumThreadsStr = getenv("TLH_NUM_THREADS");
    if (!tlhNumThreadsStr) {
        tlhNumThreadsStr = "3";
    }
    tlhNumThreads = atoi(tlhNumThreadsStr);
    if ((tlhNumThreads <= 0) || (tlhNumThreads > TLH_MAX_THREADS)) {
        fprintf(stderr, "testLibHdfs: must have a number of threads "
                "between 1 and %d inclusive, not %d\n",
                TLH_MAX_THREADS, tlhNumThreads);
        return EXIT_FAILURE;
    }
    memset(&ti[0], 0, sizeof(ti));
    for (i = 0; i < tlhNumThreads; i++) {
        ti[i].threadIdx = i;
    }

    tlhCluster = nmdCreate(&conf);
    EXPECT_NONNULL(tlhCluster);
    EXPECT_ZERO(nmdWaitClusterUp(tlhCluster));

    for (i = 0; i < tlhNumThreads; i++) {
        ti[i].theThread.start = testHdfsOperations;
        ti[i].theThread.arg = &ti[i];
        EXPECT_ZERO(threadCreate(&ti[i].theThread));
    }
    for (i = 0; i < tlhNumThreads; i++) {
        EXPECT_ZERO(threadJoin(&ti[i].theThread));
    }

    EXPECT_ZERO(nmdShutdown(tlhCluster));
    nmdFree(tlhCluster);
    return checkFailures(ti, tlhNumThreads);
}
Ejemplo n.º 10
0
void ndspExit(void)
{
	if (AtomicDecrement(&ndspRefCount)) return;
	if (!bDspReady) return;
	ndspThreadRun = false;
	if (bSleeping)
		svcSignalEvent(sleepEvent);
	threadJoin(ndspThread, U64_MAX);
	svcCloseHandle(sleepEvent);
	aptUnhook(&aptCookie);
	if (!bSleeping)
		ndspFinalize(false);
	bSleeping = false;
	bNeedsSync = false;
	dspExit();
	if (componentFree)
	{
		free((void*)componentBin);
		componentBin = NULL;
	}
}
int main(void) {

        srand(time(NULL));
	int *results[num_threads];
        int p[num_threads];
	int ids[num_threads];
	int i;
	//initialize the threading library. DON'T call this more than once!!!
	threadInit();
        set_timer();

	for(i = 0; i < num_threads; i++) {
	   //p[i] = rand()%50;
           p[i] = 0;
	   ids[i] = threadCreate(t1, (void*)&(p[i]));
//	   printf("Created thread %d.\n", ids[i]);
	}
	for(i = 0; i < num_threads; i++) {
	   threadJoin(ids[i], (void*)&(results[i]));
//	   printf("joined #%d --> %d.\n",ids[i], *(results[i]));
	}

}
Ejemplo n.º 12
0
 void CloseConnection(const SocketServer::Connection* connection) {
   shutdown(connection->socket, BOTH_DIRECTION);
   closesocket(connection->socket);
   threadJoin(connection->thread);
 }
Ejemplo n.º 13
0
bool stream_file(const std::string& filename)
{
    if (filename.empty())
    {
        print("No file selected\n");
        return true;
    }

    VGMSTREAM* vgmstream = init_vgmstream(filename.c_str());
    if (!vgmstream)
    {
        print("Bad file %s\n", filename.c_str());
        return true;
    }

    const int channels = vgmstream->channels;
    u32 buffer_size = max_samples * vgmstream->channels * sizeof(sample);

    rawSampleBuffer = static_cast<sample*>(linearAlloc(buffer_size));
    sample* buffer = static_cast<sample*>(linearAlloc(buffer_size));
    sample* buffer2 = static_cast<sample*>(linearAlloc(buffer_size));
    playBuffer1.samples = max_samples;
    playBuffer2.samples = max_samples;
    for (int i = 0; i < channels; i++)
    {
        playBuffer1.channels.push_back(buffer + i * max_samples);
        playBuffer2.channels.push_back(buffer2 + i * max_samples);
    }

    stream_filename strm_file;
    strm_file.filename = filename;
    strm_file.stream = vgmstream;

    runThreads = true;

    s32 prio = 0;
    Thread musicThread;
    Thread produceThread;
    svcGetThreadPriority(&prio, CUR_THREAD_HANDLE);
    musicThread = threadCreate(streamMusic, &strm_file, 4 * 1024, prio-1, -2, false);
    produceThread = threadCreate(decodeThread, &strm_file, 4 * 1024, prio-1, -2, false);

    bool ret = false;
    while (aptMainLoop())
    {
        hidScanInput();
        u32 kDown = hidKeysDown();
        if (kDown & KEY_START || kDown & KEY_B)
        {
            ret = kDown & KEY_START;
            break;
        }
        gfxFlushBuffers();
        gfxSwapBuffers();

        gspWaitForVBlank();
    }

    runThreads = false;
    svcSignalEvent(bufferReadyProduceRequest);
    svcSignalEvent(bufferReadyConsumeRequest);
    threadJoin(musicThread, U64_MAX);
    threadJoin(produceThread, U64_MAX);
    threadFree(musicThread);
    threadFree(produceThread);
    svcClearEvent(bufferReadyConsumeRequest);
    svcClearEvent(bufferReadyProduceRequest);


    linearFree(rawSampleBuffer);
    linearFree(buffer);
    linearFree(buffer2);
    playBuffer1.channels.clear();
    playBuffer2.channels.clear();

    close_vgmstream(vgmstream);

    return ret;
}
Ejemplo n.º 14
0
void eventloopJoin() {
	threadJoin(M->thread);
}
Ejemplo n.º 15
0
static void databaseSearchStep(DbAlignment*** dbAlignments, 
    int* dbAlignmentsLen, int type, Chain** queries, int queriesStart, 
    int queriesLen, ChainDatabase* chainDatabase, Scorer* scorer, 
    int maxAlignments, ValueFunction valueFunction, void* valueFunctionParam, 
    double valueThreshold, int* indexes, int indexesLen, int* cards, 
    int cardsLen) {
    
    Chain** database = chainDatabase->database;
    int databaseStart = chainDatabase->databaseStart;
    int databaseLen = chainDatabase->databaseLen;
    long databaseElems = chainDatabase->databaseElems;
    ChainDatabaseGpu* chainDatabaseGpu = chainDatabase->chainDatabaseGpu;
    
    int i, j, k;
    
    //**************************************************************************
    // CALCULATE CELL NUMBER
    
    long queriesElems = 0;
    for (i = 0; i < queriesLen; ++i) {
        queriesElems += chainGetLength(queries[i]);
    }
    
    if (indexes != NULL) {
    
        databaseElems = 0;
        
        for (i = 0; i < indexesLen; ++i) {
            databaseElems += chainGetLength(database[indexes[i]]);
        }
    }
    
    long long cells = (long long) queriesElems * databaseElems;
    
    //**************************************************************************
    
    //**************************************************************************
    // CALCULATE SCORES
    
    int* scores;
    
    if (cells < GPU_DB_MIN_CELLS || cardsLen == 0) {
        scoreCpu(&scores, type, queries, queriesLen, database, 
            databaseLen, scorer, indexes, indexesLen);
    } else {
        scoreDatabasesGpu(&scores, type, queries, queriesLen, chainDatabaseGpu, 
            scorer, indexes, indexesLen, cards, cardsLen, NULL);
    }
    
    //**************************************************************************
    
    //**************************************************************************
    // EXTRACT BEST CHAINS AND SAVE THEIR DATA MULTITHREADED
    
    TIMER_START("Extract best");
    
    DbAlignmentData** dbAlignmentsData = 
        (DbAlignmentData**) malloc(queriesLen * sizeof(DbAlignmentData*));

    ExtractContext* eContexts = 
        (ExtractContext*) malloc(queriesLen * sizeof(ExtractContext));
    
    for (i = 0; i < queriesLen; ++i) {
        eContexts[i].dbAlignmentData = &(dbAlignmentsData[i]);
        eContexts[i].dbAlignmentLen = &(dbAlignmentsLen[i]);
        eContexts[i].query = queries[i];
        eContexts[i].database = database;
        eContexts[i].databaseLen = databaseLen;
        eContexts[i].scores = scores + i * databaseLen;
        eContexts[i].maxAlignments = maxAlignments;
        eContexts[i].valueFunction = valueFunction;
        eContexts[i].valueFunctionParam = valueFunctionParam;
        eContexts[i].valueThreshold = valueThreshold;
        eContexts[i].cards = cards;
        eContexts[i].cardsLen = cardsLen;
    }

    if (cardsLen == 0) {

        size_t tasksSize = queriesLen * sizeof(ThreadPoolTask*);
        ThreadPoolTask** tasks = (ThreadPoolTask**) malloc(tasksSize);

        for (i = 0; i < queriesLen; ++i) {
            tasks[i] = threadPoolSubmit(extractThread, (void*) &(eContexts[i]));
        }
        
        for (i = 0; i < queriesLen; ++i) {
            threadPoolTaskWait(tasks[i]);
            threadPoolTaskDelete(tasks[i]);
        }

        free(tasks);

    } else {

        int chunks = MIN(queriesLen, cardsLen);

        int cardsChunk = cardsLen / chunks;
        int cardsAdd = cardsLen % chunks;
        int cardsOff = 0;

        int contextsChunk = queriesLen / chunks;
        int contextsAdd = queriesLen % chunks;
        int contextsOff = 0;

        size_t contextsSize = chunks * sizeof(ExtractContexts);
        ExtractContexts* contexts = (ExtractContexts*) malloc(contextsSize);

        size_t tasksSize = chunks * sizeof(Thread);
        Thread* tasks = (Thread*) malloc(tasksSize);

        for (i = 0; i < chunks; ++i) {

            int* cards_ = cards + cardsOff;
            int cardsLen_ = cardsChunk + (i < cardsAdd);
            cardsOff += cardsLen_;

            ExtractContext* contexts_ = eContexts + contextsOff;
            int contextsLen_ = contextsChunk + (i < contextsAdd);
            contextsOff += contextsLen_;

            for (j = 0; j < contextsLen_; ++j) {
                contexts_[j].cards = cards_;
                contexts_[j].cardsLen = cardsLen_;
            }

            contexts[i].contexts = contexts_;
            contexts[i].contextsLen = contextsLen_;

            threadCreate(&(tasks[i]), extractsThread, &(contexts[i]));
        }

        for (i = 0; i < chunks; ++i) {
            threadJoin(tasks[i]);
        }

        free(tasks);
        free(contexts);
    }

    free(eContexts);
    free(scores); // this is big, release immediately

    TIMER_STOP;

    //**************************************************************************
    
    //**************************************************************************
    // ALIGN BEST TARGETS MULTITHREADED
    
    TIMER_START("Database aligning");
    
    // create structure
    for (i = 0; i < queriesLen; ++i) {
        size_t dbAlignmentsSize = dbAlignmentsLen[i] * sizeof(DbAlignment*);
        dbAlignments[i] = (DbAlignment**) malloc(dbAlignmentsSize);
    }
    
    // count tasks
    int aTasksLen = 0;
    for (i = 0; i < queriesLen; ++i) {
        aTasksLen += dbAlignmentsLen[i];
    }
    
    size_t aTasksSize = aTasksLen * sizeof(ThreadPoolTask*);
    ThreadPoolTask** aTasks = (ThreadPoolTask**) malloc(aTasksSize);

    size_t aContextsSize = aTasksLen * sizeof(AlignContext);
    AlignContext* aContextsCpu = (AlignContext*) malloc(aContextsSize);
    AlignContext* aContextsGpu = (AlignContext*) malloc(aContextsSize);
    int aContextsCpuLen = 0;
    int aContextsGpuLen = 0;
    
    for (i = 0, k = 0; i < queriesLen; ++i, ++k) {
    
        Chain* query = queries[i];
        int rows = chainGetLength(query);

        for (j = 0; j < dbAlignmentsLen[i]; ++j, ++k) {
            
            DbAlignmentData data = dbAlignmentsData[i][j];
            Chain* target = database[data.idx];

            int cols = chainGetLength(target);
            long long cells = (long long) rows * cols;

            AlignContext* context;
            if (cols < GPU_MIN_LEN || cells < GPU_MIN_CELLS || cardsLen == 0) {
                context = &(aContextsCpu[aContextsCpuLen++]);
                context->cards = NULL;
                context->cardsLen = 0;
            } else {
                context = &(aContextsGpu[aContextsGpuLen++]);
            }

            context->dbAlignment = &(dbAlignments[i][j]);
            context->type = type;
            context->query = query;
            context->queryIdx = i;
            context->target = target;
            context->targetIdx = data.idx + databaseStart;
            context->value = data.value;
            context->score = data.score;
            context->scorer = scorer;
            context->cells = cells;
        }
    }
    
    LOG("Aligning %d cpu, %d gpu", aContextsCpuLen, aContextsGpuLen);

    // run cpu tasks
    int aCpuTasksLen;
    AlignContextsPacked* aContextsCpuPacked;

    if (aContextsCpuLen < 10000) {

        aCpuTasksLen = aContextsCpuLen;
        aContextsCpuPacked = NULL;

        for (i = 0; i < aCpuTasksLen; ++i) {
            aTasks[i] = threadPoolSubmit(alignThread, &(aContextsCpu[i]));
        }

    } else {

        aCpuTasksLen = aContextsCpuLen / CPU_PACKED_CHUNK;
        aCpuTasksLen += (aContextsCpuLen % CPU_PACKED_CHUNK) != 0;

        size_t contextsSize = aCpuTasksLen * sizeof(AlignContextsPacked);
        AlignContextsPacked* contexts = (AlignContextsPacked*) malloc(contextsSize);

        for (i = 0; i < aCpuTasksLen; ++i) {

            int length = MIN(CPU_PACKED_CHUNK, aContextsCpuLen - i * CPU_PACKED_CHUNK);

            contexts[i].contexts = aContextsCpu + i * CPU_PACKED_CHUNK;
            contexts[i].contextsLen = length;
        }

        for (i = 0; i < aCpuTasksLen; ++i) {
            aTasks[i] = threadPoolSubmit(alignsPackedThread, &(contexts[i]));
        }

        aContextsCpuPacked = contexts;
    }

    if (aContextsGpuLen) {

        int chunks = MIN(aContextsGpuLen, cardsLen);
        
        size_t contextsSize = chunks * sizeof(AlignContexts);
        AlignContexts* contexts = (AlignContexts*) malloc(contextsSize);

        size_t balancedSize = chunks * aContextsGpuLen * sizeof(AlignContext*);
        AlignContext** balanced = (AlignContext**) malloc(balancedSize);

        // set phony contexts, init data
        for (i = 0; i < chunks; ++i) {
            contexts[i].contexts = balanced + i * aContextsGpuLen;
            contexts[i].contextsLen = 0;
            contexts[i].cells = 0;
        }
        
        // balance tasks by round roobin, chunks are pretty small (CUDA cards)
        for (i = 0; i < aContextsGpuLen; ++i) {
        
            int minIdx = 0;
            long long min = contexts[0].cells;
            for (j = 1; j < chunks; ++j) {
                if (contexts[j].cells < min) {
                    min = contexts[j].cells;
                    minIdx = j;
                }
            }
            
            AlignContext* context = &(aContextsGpu[i]);
            contexts[minIdx].contexts[contexts[minIdx].contextsLen++] = context;
            contexts[minIdx].cells += context->cells;
        }

        // set context cards
        int cardsChunk = cardsLen / chunks;
        int cardsAdd = cardsLen % chunks;
        int cardsOff = 0;

        for (i = 0; i < chunks; ++i) {
        
            int cCardsLen = cardsChunk + (i < cardsAdd);
            int* cCards = cards + cardsOff;
            cardsOff += cCardsLen;

            for (j = 0; j < contexts[i].contextsLen; ++j) {
                contexts[i].contexts[j]->cards = cCards;
                contexts[i].contexts[j]->cardsLen = cCardsLen;
            }
        }

        size_t tasksSize = chunks * sizeof(Thread);
        Thread* tasks = (Thread*) malloc(tasksSize);

        // run gpu tasks first
        for (i = 0; i < chunks; ++i) {
            threadCreate(&(tasks[i]), alignsThread, &(contexts[i]));
        }
        
        // wait for gpu tasks to finish
        for (i = 0; i < chunks; ++i) {
            threadJoin(tasks[i]);
        }

        free(balanced);
        free(contexts);
    }

    // wait for cpu tasks
    for (i = 0; i < aCpuTasksLen; ++i) {
        threadPoolTaskWait(aTasks[i]);
        threadPoolTaskDelete(aTasks[i]);
    }

    free(aContextsCpuPacked);
    free(aContextsCpu);
    free(aContextsGpu);
    free(aTasks);
    
    TIMER_STOP;
    
    //**************************************************************************
    
    //**************************************************************************
    // CLEAN MEMORY

    for (i = 0; i < queriesLen; ++i) {
        free(dbAlignmentsData[i]);
    }
    free(dbAlignmentsData);

    //**************************************************************************
}