Esempio n. 1
0
/* Initialize SDL threading */
void init_threads(void)
{
    struct thread_entry *thread;
    int n;

    memset(cores, 0, sizeof(cores));
    memset(threads, 0, sizeof(threads));

    m = SDL_CreateMutex();

    if (SDL_LockMutex(m) == -1)
    {
        fprintf(stderr, "Couldn't lock mutex\n");
        return;
    }

    /* Initialize all IDs */
    for (n = 0; n < MAXTHREADS; n++)
        threads[n].id = THREAD_ID_INIT(n);

    /* Slot 0 is reserved for the main thread - initialize it here and
       then create the SDL thread - it is possible to have a quick, early
       shutdown try to access the structure. */
    thread = &threads[0];
    thread->stack = (uintptr_t *)"       ";
    thread->stack_size = 8;
    thread->name = "main";
    thread->state = STATE_RUNNING;
    thread->context.s = SDL_CreateSemaphore(0);
    thread->context.t = NULL; /* NULL for the implicit main thread */
    cores[CURRENT_CORE].running = thread;

    if (thread->context.s == NULL)
    {
        fprintf(stderr, "Failed to create main semaphore\n");
        return;
    }

    /* Tell all threads jump back to their start routines, unlock and exit
       gracefully - we'll check each one in turn for it's status. Threads
       _could_ terminate via remove_thread or multiple threads could exit
       on each unlock but that is safe. */

    /* Setup jump for exit */
    if (setjmp(thread_jmpbufs[0]) == 0)
    {
        THREAD_SDL_DEBUGF("Main thread: %p\n", thread);
        return;
    }

    SDL_UnlockMutex(m);

    /* Set to 'COMMAND_DONE' when other rockbox threads have exited. */
    while (threads_status < THREADS_EXIT_COMMAND_DONE)
        SDL_Delay(10);

    SDL_DestroyMutex(m);

    /* We're the main thead - perform exit - doesn't return. */
    sim_do_exit();
}
Esempio n. 2
0
BXEntitlementsManager::~BXEntitlementsManager()
{
  SDL_DestroyMutex(m_entitlementsListGuard);
  
}
Esempio n. 3
0
void EventKeyboard::destroyMutex() {

    SDL_DestroyMutex(mutexKeyData);

}
Esempio n. 4
0
mutex::~mutex()
{
	SDL_DestroyMutex(m_);
}
Esempio n. 5
0
PlayerBucket::~PlayerBucket() {
  SDL_DestroyMutex(lock);
}
Esempio n. 6
0
template <typename T> scm_queue<T>::~scm_queue()
{
    SDL_DestroyMutex    (data_mutex);
    SDL_DestroySemaphore(free_slots);
    SDL_DestroySemaphore(full_slots);
}
Esempio n. 7
0
static void RunFIFOTest(SDL_bool lock_free)
{
    SDL_EventQueue queue;
    WriterData writerData[NUM_WRITERS];
    ReaderData readerData[NUM_READERS];
    Uint32 start, end;
    int i, j;
    int grand_total;
 
    printf("\nFIFO test---------------------------------------\n\n");
    printf("Mode: %s\n", lock_free ? "LockFree" : "Mutex");

    readersDone = SDL_CreateSemaphore(0);
    writersDone = SDL_CreateSemaphore(0);

    SDL_memset(&queue, 0xff, sizeof(queue));

    InitEventQueue(&queue);
    if (!lock_free) {
        queue.mutex = SDL_CreateMutex();
    }

    start = SDL_GetTicks();
 
#ifdef TEST_SPINLOCK_FIFO
    /* Start a monitoring thread */
    if (lock_free) {
        SDL_CreateThread(FIFO_Watcher, "FIFOWatcher", &queue);
    }
#endif

    /* Start the readers first */
    printf("Starting %d readers\n", NUM_READERS);
    SDL_zero(readerData);
    SDL_AtomicSet(&readersRunning, NUM_READERS);
    for (i = 0; i < NUM_READERS; ++i) {
        char name[64];
        SDL_snprintf(name, sizeof (name), "FIFOReader%d", i);
        readerData[i].queue = &queue;
        readerData[i].lock_free = lock_free;
        SDL_CreateThread(FIFO_Reader, name, &readerData[i]);
    }

    /* Start up the writers */
    printf("Starting %d writers\n", NUM_WRITERS);
    SDL_zero(writerData);
    SDL_AtomicSet(&writersRunning, NUM_WRITERS);
    for (i = 0; i < NUM_WRITERS; ++i) {
        char name[64];
        SDL_snprintf(name, sizeof (name), "FIFOWriter%d", i);
        writerData[i].queue = &queue;
        writerData[i].index = i;
        writerData[i].lock_free = lock_free;
        SDL_CreateThread(FIFO_Writer, name, &writerData[i]);
    }
 
    /* Wait for the writers */
    while (SDL_AtomicGet(&writersRunning) > 0) {
        SDL_SemWait(writersDone);
    }
 
    /* Shut down the queue so readers exit */
    queue.active = SDL_FALSE;

    /* Wait for the readers */
    while (SDL_AtomicGet(&readersRunning) > 0) {
        SDL_SemWait(readersDone);
    }

    end = SDL_GetTicks();
 
    SDL_DestroySemaphore(readersDone);
    SDL_DestroySemaphore(writersDone);

    if (!lock_free) {
        SDL_DestroyMutex(queue.mutex);
    }
 
    printf("Finished in %f sec\n", (end - start) / 1000.f);

    printf("\n");
    for (i = 0; i < NUM_WRITERS; ++i) {
        printf("Writer %d wrote %d events, had %d waits\n", i, EVENTS_PER_WRITER, writerData[i].waits);
    }
    printf("Writers wrote %d total events\n", NUM_WRITERS*EVENTS_PER_WRITER);

    /* Print a breakdown of which readers read messages from which writer */
    printf("\n");
    grand_total = 0;
    for (i = 0; i < NUM_READERS; ++i) {
        int total = 0;
        for (j = 0; j < NUM_WRITERS; ++j) {
            total += readerData[i].counters[j];
        }
        grand_total += total;
        printf("Reader %d read %d events, had %d waits\n", i, total, readerData[i].waits);
        printf("  { ");
        for (j = 0; j < NUM_WRITERS; ++j) {
            if (j > 0) {
                printf(", ");
            }
            printf("%d", readerData[i].counters[j]);
        }
        printf(" }\n");
    }
    printf("Readers read %d total events\n", grand_total);
}
Esempio n. 8
0
Server::~Server(){
	SDL_DestroyMutex(mxClients);
	SDL_DestroyMutex(mxGoSerial);
	delete myIdServer;
}
Esempio n. 9
0
draw_maint_map::~draw_maint_map()
{
	themap = 0;
	SDL_DestroyMutex(draw_mtx);
	draw_mtx = 0;
}
Esempio n. 10
0
Mutex::~Mutex()
{
	SDL_DestroyMutex(mutex);
}
Esempio n. 11
0
File: host.c Progetto: emileb/xash3d
/*
=================
Host_InitCommon
=================
*/
void Host_InitCommon( const char* moduleName, const char* cmdLine, const char *progname, qboolean bChangeGame )
{
	char		dev_level[4];
	char		szTemp[MAX_SYSPATH];
	string		szRootPath;
#ifdef _WIN32
	MEMORYSTATUS	lpBuffer;

	lpBuffer.dwLength = sizeof( MEMORYSTATUS );
	GlobalMemoryStatus( &lpBuffer );
#endif

#ifndef __ANDROID__
	if( !(SDL_GetBasePath()) )
		Sys_Error( "couldn't determine current directory" );

	Q_strncpy(host.rootdir, SDL_GetBasePath(), sizeof(host.rootdir));

	if( host.rootdir[Q_strlen( host.rootdir ) - 1] == '/' )
		host.rootdir[Q_strlen( host.rootdir ) - 1] = 0;
#else
	Q_strncpy(host.rootdir, GAMEPATH, sizeof(host.rootdir));
#endif

#ifdef _WIN32
	host.oldFilter = SetUnhandledExceptionFilter( Sys_Crash );
	host.hInst = GetModuleHandle( NULL );
#endif
	host.change_game = bChangeGame;
	host.state = HOST_INIT; // initialzation started
	host.developer = host.old_developer = 0;

	CRT_Init(); // init some CRT functions

	// some commands may turn engine into infinity loop,
	// e.g. xash.exe +game xash -game xash
	// so we clearing all cmd_args, but leave dbg states as well
	if( cmdLine ) Sys_ParseCommandLine( cmdLine );
#ifdef _WIN32
	SetErrorMode( SEM_FAILCRITICALERRORS );	// no abort/retry/fail errors
#endif

	host.mempool = Mem_AllocPool( "Zone Engine" );

	if( Sys_CheckParm( "-console" )) host.developer = 1;
	if( Sys_CheckParm( "-dev" ))
	{
		if( Sys_GetParmFromCmdLine( "-dev", dev_level ))
		{
			if( Q_isdigit( dev_level ))
				host.developer = abs( Q_atoi( dev_level ));
			else host.developer++; // -dev == 1, -dev -console == 2
		}
		else host.developer++; // -dev == 1, -dev -console == 2
	}

	host.type = HOST_NORMAL; // predict state
	host.con_showalways = true;
#ifdef PANDORA
	if( Sys_CheckParm( "-noshouldermb" )) noshouldermb = 1;
#endif

#ifdef __ANDROID__
	if (chdir(host.rootdir) == 0)
		MsgDev(D_INFO,"%s is working directory now",host.rootdir);
	else
		MsgDev(D_ERROR,"%s is not exists",host.rootdir);
#else
	// we can specified custom name, from Sys_NewInstance
	if( SDL_GetBasePath() && !host.change_game )
	{
		Q_strncpy( szTemp, SDL_GetBasePath(), sizeof(szTemp) );
		FS_FileBase( szTemp, SI.ModuleName );
	}

	if(moduleName) Q_strncpy(SI.ModuleName, moduleName, sizeof(SI.ModuleName));

	FS_ExtractFilePath( SI.ModuleName, szRootPath );
	if( Q_stricmp( host.rootdir, szRootPath ))
	{
		Q_strncpy( host.rootdir, szRootPath, sizeof( host.rootdir ));
#ifdef _WIN32
		SetCurrentDirectory( host.rootdir );
#else
		chdir( host.rootdir );
#endif
	}
#endif

	if( SI.ModuleName[0] == '#' ) host.type = HOST_DEDICATED; 

	// determine host type
	if( progname[0] == '#' )
	{
		Q_strncpy( SI.ModuleName, progname + 1, sizeof( SI.ModuleName ));
		host.type = HOST_DEDICATED;
	}
	else Q_strncpy( SI.ModuleName, progname, sizeof( SI.ModuleName )); 

	if( host.type == HOST_DEDICATED )
	{
		// check for duplicate dedicated server
		host.hMutex = SDL_CreateMutex(  );

		if( !host.hMutex )
		{
			MSGBOX( "Dedicated server already running" );
			Sys_Quit();
			return;
		}

		Sys_MergeCommandLine( cmdLine );

		SDL_DestroyMutex( host.hMutex );
		host.hMutex = SDL_CreateSemaphore( 0 );
		if( host.developer < 3 ) host.developer = 3; // otherwise we see empty console
	}
	else
	{
		// don't show console as default
		if( host.developer < D_WARN ) host.con_showalways = false;
	}

	host.old_developer = host.developer;

	Con_CreateConsole();

	// first text message into console or log 
	MsgDev( D_NOTE, "Sys_LoadLibrary: Loading xash.dll - ok\n" );

	// startup cmds and cvars subsystem
	Cmd_Init();
	Cvar_Init();

	// share developer level across all dlls
	Q_snprintf( dev_level, sizeof( dev_level ), "%i", host.developer );
	Cvar_Get( "developer", dev_level, CVAR_INIT, "current developer level" );
	Cmd_AddCommand( "exec", Host_Exec_f, "execute a script file" );
	Cmd_AddCommand( "memlist", Host_MemStats_f, "prints memory pool information" );

	FS_Init();
	Image_Init();
	Sound_Init();

	FS_LoadGameInfo( NULL );
	Q_strncpy( host.gamefolder, GI->gamefolder, sizeof( host.gamefolder ));


	if( GI->secure )
	{
		// clear all developer levels when game is protected
		Cvar_FullSet( "developer", "0", CVAR_INIT );
		host.developer = host.old_developer = 0;
		host.con_showalways = false;
	}

	HPAK_Init();

	IN_Init();
	Key_Init();
}
Esempio n. 12
0
	static void del(SDL_mutex *m) { SDL_DestroyMutex(m); }
Esempio n. 13
0
THAVPacketQueue::~THAVPacketQueue()
{
    SDL_DestroyCond(m_pCond);
    SDL_DestroyMutex(m_pMutex);
}
Esempio n. 14
0
THMoviePictureBuffer::~THMoviePictureBuffer()
{
    SDL_DestroyCond(m_pCond);
    SDL_DestroyMutex(m_pMutex);
    sws_freeContext(m_pSwsContext);
}
Esempio n. 15
0
void audio_close(void)
{
    SDL_DestroyMutex(g_audio_mutex);
    SDL_PauseAudio(true);
    SDL_CloseAudio();
}
Esempio n. 16
0
signed ODE_Init()
{
	Quit = SDL_FALSE;
	dInitODE2(dInitFlagManualThreadCleanup);
	dSetMessageHandler(Error);
	dSetDebugHandler(Error);
	dSetErrorHandler(Error);

	World = dWorldCreate();
	Space = dHashSpaceCreate(0);
	Group = dJointGroupCreate(0);
	Step = 1.0/50.0;

	lua_getglobal(State, "World");
	int table = lua_gettop(State);

	if (!lua_isnil(State, table))
	{
	 lua_pushnil(State);
	 while (lua_next(State, table))
	 {
		const char *key = lua_tostring(State, -2);
		#define tointeger lua_tointeger(State, -1)
		#define toboolean lua_toboolean(State, -1)
		#define tonumber  lua_tonumber(State, -1)

		if (!SDL_strcasecmp(key, "FPS"))
		{
		 Step = 1.0/tonumber;
		}
		else
		if (!SDL_strcasecmp(key, "ERP"))
		{
		 dWorldSetERP(World, tonumber);
		}
		else
		if (!SDL_strcasecmp(key, "CFM"))
		{
		 dWorldSetCFM(World, tonumber);
		}
		else
		if (!SDL_strcasecmp(key, "LINEAR_DAMPING"))
		{
		 dWorldSetLinearDamping(World, tonumber);
		}
		else
		if (!SDL_strcasecmp(key, "LINEAR_DAMPING_THRESHOLD"))
		{
		 dWorldSetLinearDampingThreshold(World, tonumber);
		}
		else
		if (!SDL_strcasecmp(key, "ANGULAR_DAMPING"))
		{
		 dWorldSetAngularDamping(World, tonumber);
		}
		else
		if (!SDL_strcasecmp(key, "ANGULAR_DAMPING_THRESHOLD"))
		{
		 dWorldSetAngularDampingThreshold(World, tonumber);
		}
		else
		if (!SDL_strcasecmp(key, "MAX_ANGULAR_SPEED"))
		{
		 dWorldSetMaxAngularSpeed(World, tonumber);
		}
		else
		if (!SDL_strcasecmp(key, "CONTACT_MAX_CORRECTING_VELOCITY"))
		{
		 dWorldSetContactMaxCorrectingVel(World, tonumber);
		}
		else
		if (!SDL_strcasecmp(key, "CONTACT_SURFACE_LAYER"))
		{
		 dWorldSetContactSurfaceLayer(World, tonumber);
		}
		else
		if (!SDL_strcasecmp(key, "AUTO_DISABLE"))
		{
		 dWorldSetAutoDisableFlag(World, toboolean);
		}
		else
		if (!SDL_strcasecmp(key, "AUTO_DISABLE_LINEAR_THRESHOLD"))
		{
		 dWorldSetAutoDisableLinearThreshold(World, tonumber);
		}
		else
		if (!SDL_strcasecmp(key, "AUTO_DISABLE_ANGULAR_THRESHOLD"))
		{
		 dWorldSetAutoDisableAngularThreshold(World, tonumber);
		}
		else
		if (!SDL_strcasecmp(key, "AUTO_DISABLE_STEPS"))
		{
		 dWorldSetAutoDisableSteps(World, tointeger);
		}
		else
		if (!SDL_strcasecmp(key, "AUTO_DISABLE_TIME"))
		{
		 dWorldSetAutoDisableTime(World, tonumber);
		}
		else
		{
		 SDL_Log("World: %s does not match", key);
		}
		lua_pop(State, 1);
	 }
	}
	lua_pop(State, 1);

	Cond = SDL_CreateCond();
	if (!Cond)
	{
	 dWorldDestroy(World);
	 dSpaceDestroy(Space);
	 dJointGroupDestroy(Group);
	 SDL_perror("SDL_CreateCond");
	 return SDL_SetError("cannot create simulation signal");
	}
	Mutex = SDL_CreateMutex();
	if (!Mutex)
	{
	 dWorldDestroy(World);
	 dSpaceDestroy(Space);
	 dJointGroupDestroy(Group);
	 SDL_DestroyCond(Cond);
	 SDL_perror("SDL_CreateMutex");
	 return SDL_SetError("cannot create simulation mutex");
	}
	Thread = SDL_CreateThread(SimulationThread, "ODE", NULL);
	if (!Thread)
	{
	 dWorldDestroy(World);
	 dSpaceDestroy(Space);
	 dJointGroupDestroy(Group);
	 SDL_DestroyCond(Cond);
	 SDL_DestroyMutex(Mutex);
	 SDL_perror("SDL_CreateThread");
	 return SDL_SetError("cannot create simulation thread");
	}
	TimerID = SDL_AddTimer(Uint32(1000*Step), SimulationTimer, NULL);
	if (!TimerID)
	{
	 dWorldDestroy(World);
	 dSpaceDestroy(Space);
	 dJointGroupDestroy(Group);
	 SDL_DestroyCond(Cond);
	 SDL_DestroyMutex(Mutex);
	 SDL_perror("SDL_AddTimer");
	 return SDL_SetError("cannot create simulation timer");
	}
	return 0;
}
int abs_thread_mutex_destroy(abs_thread_mutex_t *mutex) {
  SDL_DestroyMutex(*mutex);
  return true;
}
Esempio n. 18
0
void SDLStub::destroyMutex(void *mutex) {
	SDL_DestroyMutex((SDL_mutex *)mutex);
}
Esempio n. 19
0
void LoggerExit(){
  if(_logger_file != NULL){ fclose(_logger_file); _logger_file = NULL; }
  if(_logger_mutex != NULL){ SDL_DestroyMutex(_logger_mutex); _logger_mutex = NULL; }
}
Esempio n. 20
0
/**
 * @brief Initializes the sound subsystem.
 *
 *    @return 0 on success.
 */
int sound_al_init (void)
{
   int ret;
   const ALchar* dev;
   ALuint s;
   ALint freq;
   ALint attribs[4] = { 0, 0, 0, 0 };

   /* Default values. */
   ret = 0;

   /* we'll need a mutex */
   sound_lock = SDL_CreateMutex();
   soundLock();

   /* Get the sound device. */
   dev = alcGetString( NULL, ALC_DEFAULT_DEVICE_SPECIFIER );

   /* opening the default device */
   al_device = alcOpenDevice(NULL);
   if (al_device == NULL) {
      WARN("Unable to open default sound device");
      ret = -1;
      goto snderr_dev;
   }

   /* Query EFX extension. */
   if (conf.al_efx) {
      al_info.efx = alcIsExtensionPresent( al_device, "ALC_EXT_EFX" );
      if (al_info.efx == AL_TRUE) {
         attribs[0] = ALC_MAX_AUXILIARY_SENDS;
         attribs[1] = 4;
      }
   }
   else
      al_info.efx = AL_FALSE;

   /* Create the OpenAL context */
   al_context = alcCreateContext( al_device, attribs );
   if (sound_lock == NULL) {
      WARN("Unable to create OpenAL context");
      ret = -2;
      goto snderr_ctx;
   }

   /* Clear the errors */
   alGetError();

   /* Set active context */
   if (alcMakeContextCurrent( al_context )==AL_FALSE) {
      WARN("Failure to set default context");
      ret = -4;
      goto snderr_act;
   }

   /* Get context information. */
   alcGetIntegerv( al_device, ALC_FREQUENCY, sizeof(freq), &freq );

   /* Try to enable EFX. */
   if (al_info.efx == AL_TRUE)
      al_enableEFX();
   else {
      al_info.efx_reverb = AL_FALSE;
      al_info.efx_echo   = AL_FALSE;
   }

   /* Allocate source for music. */
   alGenSources( 1, &music_source );

   /* Check for errors. */
   al_checkErr();

   /* Start allocating the sources - music has already taken his */
   source_nstack  = 0;
   source_mstack  = 0;
   while (source_nstack < SOUND_MAX_SOURCES) {
      if (source_mstack < source_nstack+1) { /* allocate more memory */
         source_mstack += 32;
         source_stack = realloc( source_stack, sizeof(ALuint) * source_mstack );
      }
      alGenSources( 1, &s );
      source_stack[source_nstack] = s;

      /* Distance model defaults. */
      alSourcef( s, AL_MAX_DISTANCE,       5000. );
      alSourcef( s, AL_ROLLOFF_FACTOR,     1. );
      alSourcef( s, AL_REFERENCE_DISTANCE, 500. );

      /* Set the filter. */
      if (al_info.efx == AL_TRUE)
         alSource3i( s, AL_AUXILIARY_SEND_FILTER, efx_directSlot, 0, AL_FILTER_NULL );

      /* Check for error. */
      if (alGetError() == AL_NO_ERROR)
         source_nstack++;
      else
         break;
   }
   /* Reduce ram usage. */
   source_mstack = source_nstack;
   source_stack  = realloc( source_stack, sizeof(ALuint) * source_mstack );
   /* Copy allocated sources to total stack. */
   source_ntotal = source_mstack;
   source_total  = malloc( sizeof(ALuint) * source_mstack );
   memcpy( source_total, source_stack, sizeof(ALuint) * source_mstack );
   /* Copy allocated sources to all stack. */
   source_nall   = source_mstack;
   source_all    = malloc( sizeof(ALuint) * source_mstack );
   memcpy( source_all, source_stack, sizeof(ALuint) * source_mstack );

   /* Set up how sound works. */
   alDistanceModel( AL_INVERSE_DISTANCE_CLAMPED );
   alDopplerFactor( 1. );
   sound_al_env( SOUND_ENV_NORMAL, 0. );

   /* Check for errors. */
   al_checkErr();

   /* we can unlock now */
   soundUnlock();

   /* debug magic */
   DEBUG("OpenAL started: %d Hz", freq);
   DEBUG("Renderer: %s", alGetString(AL_RENDERER));
   if (al_info.efx == AL_FALSE)
      DEBUG("Version: %s without EFX", alGetString(AL_VERSION));
   else
      DEBUG("Version: %s with EFX %d.%d", alGetString(AL_VERSION),
            al_info.efx_major, al_info.efx_minor);
   DEBUG();

   return 0;

   /*
    * error handling
    */
snderr_act:
   alcDestroyContext( al_context );
snderr_ctx:
   al_context = NULL;
   alcCloseDevice( al_device );
snderr_dev:
   al_device = NULL;
   soundUnlock();
   SDL_DestroyMutex( sound_lock );
   sound_lock = NULL;
   return ret;
}
Esempio n. 21
0
Logger::~Logger()
{
    if (mLogFile.is_open())
        mLogFile.close();
    SDL_DestroyMutex(mMutex);
}
Esempio n. 22
0
//a searching function used by textureSynthesis() to determine output pixel values
//returns the color to assign that pixel
Uint32 findBestMatch(hood_pyramid *inHoodPyramid, gauss_pyramid *inPyramid, gauss_pyramid *outPyramid, int curLevel, int x, int y)
{
	verboseDebug("\t\t\tBuilding output position neighborhood\n");
	hood *outHood = new hood(outPyramid, curLevel, x, y);

	//best match stuff
	hood *bestHood = NULL;
	double lastMatch = 999999999.9;
	Uint32 color = 0;
	int bestX = 0, bestY = 0;

	//others
	int w = inPyramid->getLevel(curLevel)->w, h = inPyramid->getLevel(curLevel)->h;

	verboseDebug("\t\t\tComparing neighborhoods\n");
    //Start with the multithreading stuff
	if (TEX_SYN_THREADS > 0)
	{
		SDL_mutex *mut = SDL_CreateMutex();

		//this is to make sure that no more than height threads are used
		int numThreads = (TEX_SYN_THREADS <= h) ? TEX_SYN_THREADS : h;

		//calculate how many rows to give to each thread. the first threads get the floor of the division,
		//the last one gets the remaining rows
		int firstThreadsRows = floor(float(h) / numThreads);

		//create the threads
		SDL_Thread **threads = new SDL_Thread*[TEX_SYN_THREADS];
		threadData **datas = new threadData*[TEX_SYN_THREADS];
		for( int t = 0; t < numThreads; t++)
		{
			//figure out what rows it needs to generate
			int from = firstThreadsRows * t;
			int to = firstThreadsRows * (t + 1);
			if(t == numThreads)
			{
				from = firstThreadsRows * t;
				to = h;
			}
			verboseDebug("\t\t\tthread #%d will check rows [%d, %d)\n", t, from, to);

			//create the data structure
			datas[t] = new threadData(from, to, w, curLevel, mut, outHood, inHoodPyramid, inPyramid, bestHood, &lastMatch, &color, &bestX, &bestY);
			//make the thread
			threads[t] = SDL_CreateThread(threadCheckRows, (void*)datas[t]);
		}

		//wait for them to finish
		for(int t = 0; t<numThreads; t++)
		{
			int rs = 0;
			SDL_WaitThread(threads[t], &rs);

			//my thread function will never return anything but 0 so this will never happen... I don't think anyway
			if(rs != 0)
				debug("WARNING: thread #%d returned status %d!\n", t, rs);

			//delete the data it used
			delete datas[t];
		}

		//delete the threads and datas arrays
		delete threads;
		delete datas;

		//clean it up
		SDL_DestroyMutex(mut);
	}
	else
		checkRows(0, h, w, curLevel, NULL, outHood, inHoodPyramid, inPyramid, bestHood, &lastMatch, &color, &bestX, &bestY);

	delete outHood;
	verboseDebug("\t\t\t\tBest match was %x at (%d, %d)\n", color, bestX, bestY);
	verboseDebug("\t\t\tDone\n");
	return color;
}
Esempio n. 23
0
Logger::~Logger()
{
    closeFile();
    SDL_DestroyMutex(mMutex);
}
Esempio n. 24
0
UDP_NetListener::~UDP_NetListener()
{
	cond.signalExit();
	SDL_WaitThread(thread, NULL);
	SDL_DestroyMutex(sessionsMutex);
}
Esempio n. 25
0
/*************************************
context_free
Deep free of a context_t struct
*************************************/
void context_free(context_t * context)
{
	context_t * ctx;

	context_lock_list();

	if( context->user_name ) {
		free(context->user_name);
	}
	context->user_name = NULL;
	context->in_game = false;
	context->connected = false;
	if( context->socket != 0) {
		SDLNet_TCP_Close(context->socket);
	}
	context->socket = 0;
	if( context->socket_data != 0) {
		SDLNet_TCP_Close(context->socket_data);
	}
	context->socket_data = 0;
	SDL_DestroyMutex(context->send_mutex);

	if( context->hostname ) {
		free(context->hostname);
	}
	context->hostname = NULL;
	if( context->character_name ) {
		free(context->character_name);
	}
	context->character_name = NULL;
	if( context->map ) {
		free(context->map);
	}
	context->map = NULL;
	if( context->type ) {
		free(context->type);
	}
	context->type = NULL;
	if( context->selection.id ) {
		free(context->selection.id);
	}
	context->selection.id = NULL;
	context->selection.map_coord[0] = -1;
	context->selection.map_coord[1] = -1;
	if( context->selection.map ) {
		free(context->selection.map);
	}
	context->selection.map = NULL;
	if( context->selection.inventory ) {
		free(context->selection.inventory);
	}
	context->selection.inventory = NULL;
	if( context->selection.equipment ) {
		free(context->selection.equipment);
	}
	context->selection.equipment = NULL;
	if( context->prev_map ) {
		free(context->prev_map);
	}
	context->prev_map = NULL;
	if( context->luaVM != NULL) {
		lua_close(context->luaVM);
	}
	if( context->cond != NULL) {
		SDL_DestroyCond(context->cond);
	}
	if( context->cond_mutex != NULL) {
		SDL_DestroyMutex(context->cond_mutex);
	}

	/* First context of the list */
	if( context->previous == NULL ) {
		context_list_start = context->next;
		if( context->next != NULL) {
			context->next->previous = NULL;
		}
	} else {
		context->previous->next = context->next;
		if( context->next != NULL) {
			context->next->previous = context->previous;
		}
	}

	/* Remove this context from other context's selection */
	ctx = context_list_start;
	while( ctx != NULL ) {
		if( context->id && ctx->selection.id ) {
			if (strcmp(context->id,ctx->selection.id)==0) {
				ctx->selection.id = NULL;
			}
		}
		ctx = ctx->next;
	}

	if( context->id ) {
		free(context->id);
	}
	context->id = NULL;

	/* Remove this context from the list */
	if( context == context_get_first() ) {
		context_list_start = context->next;
	} else {
		ctx = context_list_start;
		while( ctx != NULL ) {
			if( ctx->next == context ) {
				ctx->next = context->next;
				break;
			}
			ctx = ctx->next;
		}
	}

	free(context);

	context_unlock_list();
}
Esempio n. 26
0
static int
SDL_XINPUT_HapticOpenFromUserIndex(SDL_Haptic *haptic, const Uint8 userid)
{
    char threadName[32];
    XINPUT_VIBRATION vibration = { 0, 0 };  /* stop any current vibration */
    XINPUTSETSTATE(userid, &vibration);

    haptic->supported = SDL_HAPTIC_LEFTRIGHT;

    haptic->neffects = 1;
    haptic->nplaying = 1;

    /* Prepare effects memory. */
    haptic->effects = (struct haptic_effect *)
        SDL_malloc(sizeof(struct haptic_effect) * haptic->neffects);
    if (haptic->effects == NULL) {
        return SDL_OutOfMemory();
    }
    /* Clear the memory */
    SDL_memset(haptic->effects, 0,
        sizeof(struct haptic_effect) * haptic->neffects);

    haptic->hwdata = (struct haptic_hwdata *) SDL_malloc(sizeof(*haptic->hwdata));
    if (haptic->hwdata == NULL) {
        SDL_free(haptic->effects);
        haptic->effects = NULL;
        return SDL_OutOfMemory();
    }
    SDL_memset(haptic->hwdata, 0, sizeof(*haptic->hwdata));

    haptic->hwdata->bXInputHaptic = 1;
    haptic->hwdata->userid = userid;

    haptic->hwdata->mutex = SDL_CreateMutex();
    if (haptic->hwdata->mutex == NULL) {
        SDL_free(haptic->effects);
        SDL_free(haptic->hwdata);
        haptic->effects = NULL;
        return SDL_SetError("Couldn't create XInput haptic mutex");
    }

    SDL_snprintf(threadName, sizeof(threadName), "SDLXInputDev%d", (int)userid);

#if defined(__WIN32__) && !defined(HAVE_LIBC)  /* !!! FIXME: this is nasty. */
#undef SDL_CreateThread
#if SDL_DYNAMIC_API
    haptic->hwdata->thread = SDL_CreateThread_REAL(SDL_RunXInputHaptic, threadName, haptic->hwdata, NULL, NULL);
#else
    haptic->hwdata->thread = SDL_CreateThread(SDL_RunXInputHaptic, threadName, haptic->hwdata, NULL, NULL);
#endif
#else
    haptic->hwdata->thread = SDL_CreateThread(SDL_RunXInputHaptic, threadName, haptic->hwdata);
#endif
    if (haptic->hwdata->thread == NULL) {
        SDL_DestroyMutex(haptic->hwdata->mutex);
        SDL_free(haptic->effects);
        SDL_free(haptic->hwdata);
        haptic->effects = NULL;
        return SDL_SetError("Couldn't create XInput haptic thread");
    }

    return 0;
}
int MainServidor::mainPrincipal(){

	Log::getInstance()->debug("Servidor - Main Principal");

	mut=SDL_CreateMutex();
	MensajeConId* mensajeConId;
	
	printf("Escriba terminar si desea cerrar el servidor\n", usuarios->cantidadDeUsuarios()); 

	SDL_Thread* receptor=SDL_CreateThread(MainServidor::fun_recibirConexiones, "recibirConexiones", NULL);
	SDL_Thread* consola=SDL_CreateThread(MainServidor::fun_consolaDelServidor, "recibirConexiones", NULL);

	Log::getInstance()->debug("Servidor - Main Principal: se inician los thread recibirConexiones");

	while(!seDebeCerrarElServidor){

		SDL_mutexP(mut);

		if(!colaDeMensaje.empty()){

			//consumidor
			std::queue<char*>* colaDeMensajesDelUsuario;
			mensajeConId = colaDeMensaje.front();
			colaDeMensaje.pop();

			printf("Recibido del usuario:%i", mensajeConId->id);
//			printf(" el mensaje:%s\n",mensajeConId->mensaje);
			printf(" el mensaje:%s\n",mensajeConId->mensajeXml.getValor());

			// Log info
			stringstream mensajeLog; 
			mensajeLog << "Usuario " << mensajeConId->id << " Mensaje: " << mensajeConId->mensajeXml.getValor();
			mensajeLog << " SizeBytes:" << mensajeConId->mensajeXml.getSizeBytes();
			mensajeConId->mensajeXml.getId();
			mensajeConId->mensajeXml.getTipo();
			mensajeConId->mensajeXml.getValor();
			Log::getInstance()->info(mensajeLog.str());

			colaDeMensajesDelUsuario = usuarios->obtenerColaDeUsuario(mensajeConId->id);
			//TODO OJO aca deberia hacerse el delete sino perdera memoria
			//antes fallaba pues pone un puntero a un area de memoria fija y eso es incorrecto
			char* mensajeDeRespuesta = new char[100];
			//VALIDAR mensaje

			int res = Protocolo::validarMensaje(mensajeConId->mensajeXml);
			Protocolo::logInformacionSobreError(res);

			if (res < 0){
				sprintf(mensajeDeRespuesta,"mensaje con id <%d> es Invalido",mensajeConId->mensajeXml.getId());
			}
			else{
				sprintf(mensajeDeRespuesta,"mensaje con id <%d> procesado OK",mensajeConId->mensajeXml.getId());
			}

			SDL_mutexP(mut);
			colaDeMensajesDelUsuario->push(mensajeDeRespuesta);
			SDL_mutexV(mut);
			delete mensajeConId;
		}

		SDL_mutexV(mut);
		SDL_Delay(100);//No quiero tener permanentemente bloqueada la cola para revisar si llego algo.
	}

	Log::getInstance()->info("Se solicito la detención del Server.");

	SDL_WaitThread(receptor, NULL);
	SDL_WaitThread(consola, NULL);

	Log::getInstance()->debug("Servidor - Main Principal: esperando que los threads finalicen.");

	SDL_DestroyMutex(mut);
	SDL_Delay(5000);

	Log::getInstance()->debug("Servidor - Main Principal: se liberaron los recursos.");

	return 0;
}
Esempio n. 28
0
static void FreeResources(void)
{
    OPL_Queue_Destroy(callback_queue);
    SDL_DestroyMutex(callback_queue_mutex);
    SDL_DestroyMutex(timer_mutex);
}
Esempio n. 29
0
IRCLobby::~IRCLobby()
{
    stopThread();
    SDL_DestroyMutex(game_servers_mutex);
}
Esempio n. 30
0
int Runtime::runShell(const char *startupBas, int fontScale, int debugPort) {
  logEntered();

  os_graphics = 1;
  os_color_depth = 16;
  opt_interactive = true;
  opt_usevmt = 0;
  opt_file_permitted = 1;
  opt_graphics = true;
  opt_pref_bpp = 0;
  opt_nosave = true;

  _output->setTextColor(DEFAULT_FOREGROUND, DEFAULT_BACKGROUND);
  _output->setFontSize(getStartupFontSize(_window));
  _initialFontSize = _output->getFontSize();
  if (fontScale != 100) {
    _fontScale = fontScale;
    int fontSize = (_initialFontSize * _fontScale / 100);
    _output->setFontSize(fontSize);
  }

  SDL_Init(SDL_INIT_AUDIO);
  SDL_AudioSpec desiredSpec;
  desiredSpec.freq = FREQUENCY;
  desiredSpec.format = AUDIO_S16SYS;
  desiredSpec.channels = 1;
  desiredSpec.samples = 2048;
  desiredSpec.callback = audio_callback;

  SDL_AudioSpec obtainedSpec;
  SDL_OpenAudio(&desiredSpec, &obtainedSpec);
  net_init();

  if (debugPort > 0) {
    appLog("Debug active on port %d\n", debugPort);
    g_lock = SDL_CreateMutex();
    g_cond = SDL_CreateCond();
    opt_trace_on = 1;
    g_debugBreak = SDL_TRUE;
    SDL_Thread *thread =
      SDL_CreateThread(debugThread, "DBg", (void *)(intptr_t)debugPort);
    SDL_DetachThread(thread);
  }

  if (startupBas != NULL) {
    String bas = startupBas;
    if (opt_ide == IDE_INTERNAL) {
      runEdit(bas.c_str());
    } else {
      runOnce(bas.c_str());
    }
    while (_state == kRestartState) {
      _state = kActiveState;
      if (_loadPath.length() != 0) {
        bas = _loadPath;
      }
      runOnce(bas.c_str());
    }
  } else {
    runMain(MAIN_BAS);
  }

  if (debugPort > 0) {
    SDL_DestroyCond(g_cond);
    SDL_DestroyMutex(g_lock);
  }

  debugStop();
  net_close();
  SDL_CloseAudio();
  _state = kDoneState;
  logLeaving();
  return _fontScale;
}