Пример #1
0
int main()
{

    cond = CondCreate("cond");
    tid1 = threadCreate("test1", test1);
    tid2 = threadCreate("test2", test2);
   
    return 0;
}
Пример #2
0
void OSystem_3DS::initEvents() {
	eventMutex = new Common::Mutex();
	s32 prio = 0;
	svcGetThreadPriority(&prio, CUR_THREAD_HANDLE);
	_timerThread = threadCreate(&timerThreadFunc, this, 32 * 1024, prio - 1, -2, false);
	_eventThread = threadCreate(&eventThreadFunc, &_eventQueue, 32 * 1024, prio - 1, -2, false);

	aptHook(&cookie, aptHookFunc, this);
}
Пример #3
0
Result task_capture_cam(capture_cam_data* data) {
    if(data == NULL || data->buffer == NULL || data->width <= 0 || data->width > 640 || data->height <= 0 || data->height > 480) {
        return R_APP_INVALID_ARGUMENT;
    }

    data->mutex = 0;

    data->finished = false;
    data->result = 0;
    data->cancelEvent = 0;

    Result res = 0;

    if(R_SUCCEEDED(res = svcCreateEvent(&data->cancelEvent, RESET_STICKY)) && R_SUCCEEDED(res = svcCreateMutex(&data->mutex, false))) {
        if(threadCreate(task_capture_cam_thread, data, 0x10000, 0x1A, 0, true) == NULL) {
            res = R_APP_THREAD_CREATE_FAILED;
        }
    }

    if(R_FAILED(res)) {
        data->finished = true;

        if(data->cancelEvent != 0) {
            svcCloseHandle(data->cancelEvent);
            data->cancelEvent = 0;
        }

        if(data->mutex != 0) {
            svcCloseHandle(data->mutex);
            data->mutex = 0;
        }
    }

    return res;
}
Пример #4
0
static void databaseSearch(DbAlignment*** dbAlignments, int* dbAlignmentsLen, 
    int type, Chain** queries, int queriesLen, ChainDatabase* chainDatabase, 
    Scorer* scorer, int maxAlignments, ValueFunction valueFunction, 
    void* valueFunctionParam, double valueThreshold, int* indexes, 
    int indexesLen, int* cards, int cardsLen, Thread* thread) {
    
    Context* param = (Context*) malloc(sizeof(Context));
    
    param->dbAlignments = dbAlignments;
    param->dbAlignmentsLen = dbAlignmentsLen;
    param->type = type;
    param->queries = queries;
    param->queriesLen = queriesLen;
    param->chainDatabase = chainDatabase;
    param->scorer = scorer;
    param->maxAlignments = maxAlignments;
    param->valueFunction = valueFunction;
    param->valueFunctionParam = valueFunctionParam;
    param->valueThreshold = valueThreshold;
    param->indexes = indexes;
    param->indexesLen = indexesLen;
    param->cards = cards;
    param->cardsLen = cardsLen;
    
    if (thread == NULL) {
        databaseSearchThread(param);
    } else {
        threadCreate(thread, databaseSearchThread, (void*) param);
    }
}
Пример #5
0
 THREAD_ROUTINE_RETURN SocketServer::HandleConnections(void* data)
 {
    SocketServer* server = (SocketServer*) data;
    std::vector<SocketServer::Connection*> clients;
    struct sockaddr_storage client_addr;
    socklen_t addr_size = sizeof(client_addr);
    MutexHandle lock;
    mutexCreate(&lock);
    int client_socket;

    while (!server->shutdown_) {
      if ((client_socket = accept(server->socket_, (struct sockaddr*)&client_addr, &addr_size)) > 0) {
        clients.push_back(new jsonrpc::SocketServer::Connection());
        clients.back()->socket = client_socket;
        clients.back()->pserver = server;
        clients.back()->plock_server = &lock;
        CloseFinishedConnections(clients);
        if (clients.size() > server->poolSize_) {
          CloseOldestConnection(clients);
        }
        threadCreate(&clients.back()->thread, (ThreadStartRoutine)ConnectionHandler, clients.back());
      }
    }
    CloseAllConnections(clients);
    mutexDestroy(&lock);
    return 0;
  }
Пример #6
0
Result task_data_op(data_op_data* data) {
    if(data == NULL) {
        return R_APP_INVALID_ARGUMENT;
    }

    data->processed = 0;

    data->currProcessed = 0;
    data->currTotal = 0;

    data->finished = false;
    data->result = 0;
    data->cancelEvent = 0;

    Result res = 0;
    if(R_SUCCEEDED(res = svcCreateEvent(&data->cancelEvent, RESET_STICKY))) {
        if(threadCreate(task_data_op_thread, data, 0x10000, 0x18, 1, true) == NULL) {
            res = R_APP_THREAD_CREATE_FAILED;
        }
    }

    if(R_FAILED(res)) {
        data->finished = true;

        if(data->cancelEvent != 0) {
            svcCloseHandle(data->cancelEvent);
            data->cancelEvent = 0;
        }
    }

    aptSetSleepAllowed(false);

    return res;
}
Пример #7
0
Result task_populate_files(populate_files_data* data) {
    if(data == NULL || data->items == NULL) {
        return R_FBI_INVALID_ARGUMENT;
    }

    task_clear_files(data->items);

    data->finished = false;
    data->result = 0;
    data->cancelEvent = 0;

    Result res = 0;
    if(R_SUCCEEDED(res = svcCreateEvent(&data->cancelEvent, RESET_STICKY))) {
        if(threadCreate(task_populate_files_thread, data, 0x10000, 0x19, 1, true) == NULL) {
            res = R_FBI_THREAD_CREATE_FAILED;
        }
    }

    if(R_FAILED(res)) {
        data->finished = true;

        if(data->cancelEvent != 0) {
            svcCloseHandle(data->cancelEvent);
            data->cancelEvent = 0;
        }
    }

    return res;
}
Пример #8
0
Handle task_populate_pending_titles(list_item* items, u32* count, u32 max) {
    if(items == NULL || count == NULL || max == 0) {
        return 0;
    }

    task_clear_pending_titles(items, count);

    populate_pending_titles_data* data = (populate_pending_titles_data*) calloc(1, sizeof(populate_pending_titles_data));
    data->items = items;
    data->count = count;
    data->max = max;

    Result eventRes = svcCreateEvent(&data->cancelEvent, 1);
    if(R_FAILED(eventRes)) {
        error_display_res(NULL, NULL, eventRes, "Failed to create pending title list cancel event.");

        free(data);
        return 0;
    }

    if(threadCreate(task_populate_pending_titles_thread, data, 0x4000, 0x18, 1, true) == NULL) {
        error_display(NULL, NULL, "Failed to create pending title list thread.");

        svcCloseHandle(data->cancelEvent);
        free(data);
        return 0;
    }

    return data->cancelEvent;
}
Пример #9
0
void ThreadTest()
{   
    int tid;
    tid = threadCreate("smr", SimpleThread); /* Creating a thread */
    n_printf("Entering SimpleTest");
    SimpleThread(2); /* Calling the function with argument 
                                        to distinguish between the threads */
}
Пример #10
0
Result ndspInit(void)
{
	Result rc = 0;
	if (AtomicPostIncrement(&ndspRefCount)) return 0;

	if (!componentBin && !ndspFindAndLoadComponent())
	{
		rc = MAKERESULT(RL_PERMANENT, RS_NOTFOUND, 41, RD_NOT_FOUND);
		goto _fail0;
	}

	LightLock_Init(&ndspMutex);
	ndspInitMaster();
	ndspiInitChn();

	rc = cfguInit();
	if (R_SUCCEEDED(rc))
	{
		u8 outMode;
		rc = CFGU_GetConfigInfoBlk2(sizeof(outMode), 0x70001, &outMode);
		if (R_SUCCEEDED(rc))
			ndspMaster.outputMode = outMode;
		cfguExit();
	}

	rc = dspInit();
	if (R_FAILED(rc)) return rc;

	rc = ndspInitialize(false);
	if (R_FAILED(rc)) goto _fail1;

	rc = svcCreateEvent(&sleepEvent, 0);
	if (R_FAILED(rc)) goto _fail2;

	ndspThread = threadCreate(ndspThreadMain, 0x0, NDSP_THREAD_STACK_SIZE, 0x18, -2, true);
	if (!ndspThread) goto _fail3;

	aptHook(&aptCookie, ndspAptHook, NULL);
	return 0;

_fail3:
	svcCloseHandle(sleepEvent);
_fail2:
	ndspFinalize(false);
_fail1:
	dspExit();
	if (componentFree)
	{
		free((void*)componentBin);
		componentBin = NULL;
	}
_fail0:
	AtomicDecrement(&ndspRefCount);
	return rc;
}
Пример #11
0
void OSystem_3DS::initAudio() {
	_mixer = new Audio::MixerImpl(this, 22050);

	hasAudio = R_SUCCEEDED(ndspInit());
	_mixer->setReady(false);

	if (hasAudio) {
		s32 prio = 0;
		svcGetThreadPriority(&prio, CUR_THREAD_HANDLE);
		audioThread = threadCreate(&audioThreadFunc, _mixer, 32 * 1048, prio - 1, -2, false);
	}
}
Пример #12
0
DWORD WINAPI mailThread(LPVOID arg) {

	char buffer[1024];
	planet_type *planet = (planet_type*)malloc(sizeof(planet_type));
	DWORD bytesRead;
	static int posY = 0;
	char mailSlotString[18] = "\\\\.\\mailslot\\", inputString[1024];
	HANDLE serverMailslot;

							/* create a mailslot that clients can use to pass requests through   */
							/* (the clients use the name below to get contact with the mailslot) */
							/* NOTE: The name of a mailslot must start with "\\\\.\\mailslot\\"  */
	

	serverMailslot = mailslotCreate("\\\\.\\mailslot\\serverMailslot");
	if (serverMailslot == INVALID_HANDLE_VALUE)
	{
		MessageBox(0, "Could not create mailslot, exiting.", "Error", 1);
		Sleep(3000);
		exit(1);
	}

							/* (ordinary file manipulating functions are used to read from mailslots) */
							/* in this example the server receives strings from the client side and   */
							/* displays them in the presentation window                               */
							/* NOTE: binary data can also be sent and received, e.g. planet structures*/
 
	while (1)
	{
		bytesRead = mailslotRead(serverMailslot, (void *)planet, sizeof(planet_type));

		if (bytesRead != 0) {
			// If planet name doesnt exist, add it to linked list
			if (!planetExists(planet)) {
				EnterCriticalSection(&dbAccess);
				InsertAtHead(*planet);
				LeaveCriticalSection(&dbAccess);
				threadCreate(calculatePosition, &(head->data));
			}
			else
			{
				sendErrorToCreator(planet, 2);
			}
		}
		else {
			/* failed reading from mailslot                              */
			/* (in this example we ignore this, and happily continue...) */
		}
	}
  
	free(planet);
	return 0;
}
Пример #13
0
t_ilm_bool SystemdHealthMonitor::start()
{
    LOG_INFO("SystemdHealthMonitor", "starting");
    t_ilm_bool result = ILM_TRUE;
    if (watchdogEnabled())
    {
        result &= threadCreate();
        result &= threadInit();
        result &= threadStart();
    }
    reportStartupComplete();
    return result;
}
Пример #14
0
Result gspInitEventHandler(Handle _gspEvent, vu8* _gspSharedMem, u8 gspThreadId)
{
	// Initialize events
	int i;
	for (i = 0; i < GSPGPU_EVENT_MAX; i ++)
		LightEvent_Init(&gspEvents[i], RESET_STICKY);

	// Start event thread
	gspEvent = _gspEvent;
	gspEventData = _gspSharedMem + gspThreadId*0x40;
	gspRunEvents = true;
	gspEventThread = threadCreate(gspEventThreadMain, 0x0, GSP_EVENT_STACK_SIZE, 0x31, -2, true);
	return 0;
}
Пример #15
0
int workerPoolInit(int threadNum) {
	struct workerPool *pool = (struct workerPool*)zcalloc(sizeof(*pool));
	pool->threadNum = threadNum; 
	pool->sleepThreadNum = 0;
	pool->threads = (struct thread**)zcalloc(sizeof(struct thread*)*threadNum);
	pool->running = 0;
	int i;
	for (i = 0; i < pool->threadNum; i++) {
		pool->threads[i] = threadCreate(handle, "");
	}

	pool->queue = contextQueueCreate(1024);
	pthread_mutex_init(&pool->lock, NULL);
	pthread_cond_init(&pool->cond, NULL);
	M = pool;
	return 0;
}
Пример #16
0
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdLine, int nCmdShow ) {

	HWND hWnd;
	DWORD threadID;
	MSG msg;

	if (!InitializeCriticalSectionAndSpinCount(&dbAccess, 0x00000400)) 
		return 0;

							/* Create the window, 3 last parameters important */
							/* The tile of the window, the callback function */
							/* and the backgrond color */

	hWnd = windowCreate (hPrevInstance, hInstance, nCmdShow, "Universe", MainWndProc, COLOR_WINDOW+1);

							/* start the timer for the periodic update of the window    */
							/* (this is a one-shot timer, which means that it has to be */
							/* re-set after each time-out) */
							/* NOTE: When this timer expires a message will be sent to  */
							/*       our callback function (MainWndProc).               */
  
	windowRefreshTimer (hWnd, UPDATE_FREQ);
  

							/* create a thread that can handle incoming client requests */
							/* (the thread starts executing in the function mailThread) */
							/* NOTE: See online help for details, you need to know how  */ 
							/*       this function does and what its parameters mean.   */
							/* We have no parameters to pass, hence NULL				*/
  

	threadID = threadCreate (mailThread, NULL); 
  

							/* (the message processing loop that all windows applications must have) */
							/* NOTE: just leave it as it is. */
	while( GetMessage( &msg, NULL, 0, 0 ) ) {
		TranslateMessage( &msg );
		DispatchMessage( &msg );
	}

	DeleteCriticalSection(&dbAccess);
	return msg.wParam;
}
Пример #17
0
// startMusic: Plays a song with network streaming feature
void startMusic(Socket* sock, Music* src)
{
	closeStream = false;
	src->streamLoop = false; // TODO: Add looping feature
	songPointer = 0;
	netSize = 0;
	u32 ch = 0x08;
	u32 ch2 = 0x09;
	bool non_native_encode = false;
	ThreadFunc streamFunction = streamWAV;
	u8 tmp_encode;
	/*if (src->encoding == CSND_ENCODING_VORBIS){
		streamFunction = streamOGG;
		tmp_encode = src->encoding;
		src->encoding = CSND_ENCODING_PCM16;
		non_native_encode = true;
	}*/
	int raw_format;
	if (src->audiotype == 1) raw_format = NDSP_FORMAT_MONO_PCM16;
	else raw_format = NDSP_FORMAT_STEREO_PCM16;
	ndspChnReset(ch);
	ndspChnWaveBufClear(ch);
	ndspChnSetInterp(ch, NDSP_INTERP_LINEAR);
	ndspChnSetRate(ch, float(src->samplerate));
	ndspChnSetFormat(ch, raw_format);
	ndspWaveBuf* waveBuf = (ndspWaveBuf*)calloc(1, sizeof(ndspWaveBuf));
	createDspBlock(waveBuf, src->bytepersample, src->mem_size, 0, (u32*)src->audiobuf);
	src->blocks = NULL;
	populatePurgeTable(src, waveBuf);
	ndspChnWaveBufAdd(ch, waveBuf);
	src->tick = osGetTime();
	src->wavebuf = waveBuf;
	src->ch = ch;
	src->isPlaying = true;
	src->lastCheck = ndspChnGetSamplePos(ch);
	src->streamLoop = false;
	svcCreateEvent(&updateStream,0);
	cachePackage* pkg = (cachePackage*)malloc(sizeof(cachePackage));
	pkg->client = sock;
	pkg->song = src;
	svcSignalEvent(updateStream);
	threadCreate(streamFunction, pkg, 8192, 0x18, 0, true);
	src->isPlaying = true;
}
Пример #18
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);
}
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]));
	}

}
Пример #20
0
extern int threadPoolInitialize(int n) {

    if (threadPool != NULL) {
        return 0;
    }

    if (n < 1) {
        return -1;
    }
    
    Thread* threads = (Thread*) malloc(n * sizeof(Thread));
    
    int maxLength = QUEUE_MAX_SIZE;
    size_t queueSize = maxLength * sizeof(ThreadPoolTask);
    ThreadPoolTask** queue = (ThreadPoolTask**) malloc(queueSize);
    
    threadPool = (ThreadPool*) malloc(sizeof(ThreadPool));
    threadPool->terminated = 0;
    threadPool->threads = threads;
    threadPool->threadsLen = n;
    threadPool->queue.data = queue;
    threadPool->queue.length = 0;
    threadPool->queue.maxLength = maxLength;
    threadPool->queue.current = 0;
    threadPool->queue.last = 0;
    threadPool->queue.full = 0;
    semaphoreCreate(&(threadPool->queue.mutex), 1);
    semaphoreCreate(&(threadPool->queue.wait), 0);
    semaphoreCreate(&(threadPool->queue.submit), 0);

    int i;
    for (i = 0; i < n; ++i) {
        threadCreate(&(threads[i]), worker, NULL);
    }

    return 0;
}
Пример #21
0
DWORD WINAPI mailThread(LPVOID arg) {

	char buffer[1024];
	DWORD bytesRead;
	static int posY = 0;
	int flag = 0;
	HANDLE mailbox;
							/* create a mailslot that clients can use to pass requests through   */
							/* (the clients use the name below to get contact with the mailslot) */
							/* NOTE: The name of a mailslot must start with "\\\\.\\mailslot\\"  */

	
	mailbox = mailslotCreate ("\\\\.\\mailslot\\mailbox");

	InitializeCriticalSection(&criticalSection);
	for(;;) {				
							/* (ordinary file manipulating functions are used to read from mailslots) */
							/* in this example the server receives strings from the client side and   */
							/* displays them in the presentation window                               */
							/* NOTE: binary data can also be sent and received, e.g. planet structures*/
		
		bytesRead = mailslotRead (mailbox, &buffer, strlen(buffer)); 
		//TESTING PLANETS
		//if(flag==0)
		//{
		//	planet_type p1 = { "p1", 300, 300, 0, 0, 1000000000, NULL, 1000, NULL };
		//	planet_type p2 = { "p2", 200, 300, 0, 0.008, 1000, NULL, 1000, NULL};
		//	planet_type p3 = { "p3", 210, 300, 0.008, 0.008, 5000000, NULL, 1000, NULL };
		//	planet_type *p11 = malloc(sizeof(planet_type));
		//	memcpy(p11, &p1, sizeof(planet_type));
		//	p11->next = NULL;
		//	planet_type *p22 = malloc(sizeof(planet_type));
		//	memcpy(p22, &p2, sizeof(planet_type));
		//	p22->next = NULL;
		//	planet_type *p33 = malloc(sizeof(planet_type));
		//	memcpy(p33, &p3, sizeof(planet_type));
		//	p33->next = NULL;
		//	addPlanet(p11);
		//	addPlanet(p22);
		//	addPlanet(p33);
		//	threadCreate((LPTHREAD_START_ROUTINE)planetThread, p11);
		//	threadCreate((LPTHREAD_START_ROUTINE)planetThread, p22);
		//	threadCreate((LPTHREAD_START_ROUTINE)planetThread, p33);
		//	flag = 1;
		//}
		//Create planet
		if (bytesRead != 0) {
			planet_type *p = malloc(sizeof(planet_type));
			memcpy(p, buffer, sizeof(planet_type));
			p->next = NULL;
			addPlanet(p);
			threadCreate((LPTHREAD_START_ROUTINE)planetThread, p);
			
		

							/* NOTE: It is appropriate to replace this code with something */
							/*       that match your needs here.                           */
		posY++;  
							/* (hDC is used reference the previously created window) */	
		TextOut(hDC, 10, 50+posY%200, p->name, sizeof(strlen(p->name)));

		
		}
		else {
								/* failed reading from mailslot                              */
								/* (in this example we ignore this, and happily continue...) */
		}
	}
	DeleteCriticalSection(&criticalSection);
  return 0;
}
Пример #22
0
 bool SocketServer::StartListening()
 {
   CreateSocket();
   shutdown_ = false;
   return threadCreate(&server_thread_, (ThreadStartRoutine)HandleConnections, this) == 0;
 }
Пример #23
0
int eventloopInit(int setsize) {
	M = (struct eventloop *)zmalloc(sizeof(*M));
	M->eventloop = aeCreateEventLoop(setsize);
	M->thread = threadCreate(run, "eventloop");
	return 0;
}
Пример #24
0
int main(int argc, char *argv[])
{
    //Initialize variables to be used later
    simulatorStructure simulator;
    taskInfoBlock test;
    processControlBlock *process = NULL, *currentProcess = NULL, *tempPCB = NULL;
    interrupted = 0;
    int maxTimeProcessing = 0;
    List log;
    char logBuffer [100];
    FILE *output;
    ListNode *tempNode = NULL;
    
    // initializes log to print info to
    // log will print to file or terminal -at the end of the program- depending on the config file
    init(&log);
    
    // Check if configuration file isn't provided
    if(argc != 2) 
    {
        // Display error
        puts("Error: Invalid parameters");
        
        // End program with error
        return 1;
    }
    
    // Read into simulator configuration struct
    // Check if getting simulator configuration failed
    if(!getSimulatorConfiguration(&simulator, argv[1])) 
    {
        // Display error
        puts("Error: Invalid configuration file");
        
        // End program with error
        return 1;
    }
    
    // assign maximum allowed processing time from the simulator configuration
    maxTimeProcessing = (simulator.quantum * simulator.processorCycleTime * 1000);

    // Create process queue
    // Check if creating process queue failed
    if(!createProcessQueue(&process, simulator.processFilePath)) 
    {
        // Display error
        puts("Error: Failed to create job queue");
        
        // End program with error
        return 1;
    }
    
    // Set current process
    currentProcess = &process[0];
    
    // begin writing to log
    insert(&log, "System Start 0 (microsec)\n");
    
    // Begin Simulation Loop and go until no processes remain
    while(currentProcess != NULL)
    {
        // Set process's arrival time if not already set
        if(currentProcess->arrivalTime == 0)
        {
            currentProcess->arrivalTime = time(NULL);
        }

        // if a thread throws an interrupt
        if(interrupted == 1)
        {
            tempPCB = currentProcess;

            //search for the process whose I/O just finished
            while(tempPCB->ioInterrupted == false)
            {
                tempPCB = tempPCB->nextPCB;
            }

            //reset Finished and Interrupted so that the process can continue being processed
            tempPCB->ioFinished = true;
            tempPCB->ioInterrupted = false;

            //reset interrupt flag
            interrupted = 0;
        }

        //Process current task by busy waiting
        // if not blocked for I/O wait, continue to process next job
        if( currentProcess->ioFinished && currentProcess->currentJob < currentProcess->numberOfJobs)
        {
            // if a process has a CPU operation
            if(currentProcess->jobs[currentProcess->currentJob].operation == 'P') 
            {
                // Sleep
                //if the quantum time is less than the remaining job time, take the entire quantum
                if(simulator.quantum < currentProcess->jobs[currentProcess->currentJob].cyclesRemaining)
                {
                    //write to log
                    sprintf(logBuffer, "PID %d: CPU Process %d (microsec)", currentProcess->pid, maxTimeProcessing);
                    insert(&log, logBuffer);

                    //sleep for maximum time
                    usleep(maxTimeProcessing);
                    
                    // Subtract quantum time from process
                    currentProcess->timeRemaining -= simulator.quantum;
                    currentProcess->jobs[currentProcess->currentJob].cyclesRemaining -= simulator.quantum;
                }
                //if the quantum is greater than required time, finish the job
                else
                {
                     // write to log
                     sprintf(logBuffer, "PID %d: CPU Process %d (microsec)", currentProcess->pid, currentProcess->jobs[currentProcess->currentJob].cyclesRemaining * simulator.processorCycleTime * 1000);
                     insert(&log, logBuffer);

                     // sleep for remaining job time
                     usleep(currentProcess->jobs[currentProcess->currentJob].cyclesRemaining * simulator.processorCycleTime * 1000);
                     
                     // Subtract time run from process
                     currentProcess->timeRemaining -= currentProcess->jobs[currentProcess->currentJob].cyclesRemaining;
                     currentProcess->jobs[currentProcess->currentJob].cyclesRemaining -= currentProcess->jobs[currentProcess->currentJob].cyclesRemaining;
                }
            }

            // if a process has an I/O operation
            else
            {
                
                // output to log
                sprintf(logBuffer, "PID %d: Began %s I/O Process", currentProcess->pid, currentProcess->jobs[currentProcess->currentJob].name);
                insert(&log, logBuffer);

                // set ioFinished to false so this process will be skipped in the queue
                currentProcess->ioFinished = false;

                // write reassurance the program is working to the terminal
                printf("Working...\n");

                currentProcess->threadBeingCreated = true;

                // create thread
                threadCreate(&currentProcess, simulator, &log);

                // wait for thread to finish creating itself
                // weird errors happen to process if not made to wait for thread creation
                while(currentProcess->threadBeingCreated);

            }
        }
        
        //If the currentProcess's job is finished, delete it
        if( currentProcess->jobs[currentProcess->currentJob].cyclesRemaining <= 0 )
        {
            if(currentProcess->currentJob < currentProcess->numberOfJobs)
            {
                currentProcess->currentJob++;
            }
        }
        
        //Delete the process if it is done
        if( currentProcess->timeRemaining <= 0 && currentProcess->ioInterrupted == false && currentProcess->ioFinished == true)
        {
            sprintf(logBuffer, "PID %d: finished", currentProcess->pid);
            insert(&log, logBuffer);
            currentProcess = deleteProcess( currentProcess );  
        } 
            
        //Get the next process, context switch
        //context switches do not get printed because they happen so many times in larger processes that it takes up the entire log file
        else
        {
            setCurrentProcess(&currentProcess, simulator);
        }         
    }

    //last log output
    insert(&log, "\nSystem End 0 (microsec)");

    //Print output to monitor if specified by the configuration file
    if(strcmp(simulator.logType, "Log to Monitor") == 0 || strcmp(simulator.logType, "Log to Both") == 0)
    {
        print(&log);
    }
    
    //Print output to log file if specified by the configuration file
    if(strcmp(simulator.logType, "Log to File") == 0 || strcmp(simulator.logType, "Log to Both") == 0)
    {
        //Open the output log file
        output = fopen("Log.txt", "w");

        //Check to see that the linked list is not empty
        if(!empty(&log))
        {
            //Print the first node
            tempNode = log.head;
            fprintf(output, "%s\n", tempNode->dataItem);
    
            //Iterate through the linked list
            while(tempNode->next != 0)
            {
                //Go to the next node
                tempNode = tempNode->next;
    
                //Print the next node
                fprintf(output, "%s\n", tempNode->dataItem);
            }
        }
        
        //Close the output file
        fclose(output);
    }

    // Free memory
    free(simulator.version);
    free(simulator.processorScheduling);
    free(simulator.processFilePath);
    free(simulator.memoryType);
    free(simulator.logType);
    
    //End the program
    return 0;
}
Пример #25
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);

    //**************************************************************************
}
Пример #26
0
Result aptInit(void)
{
	Result ret=0;

	if (AtomicPostIncrement(&aptRefCount)) return 0;

	// Initialize APT stuff, escape load screen.
	ret = __apt_initservicehandle();
	if(R_FAILED(ret)) goto _fail;
	if(R_FAILED(ret=APT_GetLockHandle(0x0, &aptLockHandle))) goto _fail;
	svcCloseHandle(aptuHandle);

	currentAppId = envGetAptAppId();

	svcCreateEvent(&aptStatusEvent, 0);
	svcCreateEvent(&aptSleepSync, 0);
	LightLock_Init(&aptStatusMutex);
	aptStatus=0;

	if(!aptIsCrippled())
	{
		aptOpenSession();
		if(R_FAILED(ret=APT_Initialize(currentAppId, &aptEvents[0], &aptEvents[1])))return ret;
		aptCloseSession();
		
		aptOpenSession();
		if(R_FAILED(ret=APT_Enable(0x0))) goto _fail;
		aptCloseSession();
		
		// create APT close event
		svcCreateEvent(&aptEvents[2], 0);

		// After a cycle of APT_Finalize+APT_Initialize APT thinks the
		// application is suspended, so we need to tell it to unsuspend us.
		if (aptIsReinit())
		{
			aptOpenSession();
			APT_PrepareToJumpToApplication(0x0);
			aptCloseSession();

			aptOpenSession();
			APT_JumpToApplication(0x0, 0x0, 0x0);
			aptCloseSession();
		}
		
		aptOpenSession();
		if(R_FAILED(ret=APT_NotifyToWait(currentAppId)))goto _fail;
		aptCloseSession();

		// create APT event handler thread
		aptEventHandlerThread = threadCreate(aptEventHandler, 0x0, APT_HANDLER_STACKSIZE, 0x31, -2, true);

		// Wait for the state to become APT_RUNNING
		aptWaitStatusEvent();
	} else
		aptAppStarted();

	return 0;

_fail:
	AtomicDecrement(&aptRefCount);
	return ret;
}
Пример #27
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;
}