Example #1
0
cFUThread::cFUThread(THREAD_ROUTINE_POINTER startAddress, void* parameter, bool suspended, const char* szName)
:	isSuspended(suspended)
,	isSuspendedCS()
,	semaphore()
,	threadStartedSemaphore()
,	terminate(false)
,	exitCode(0)
#ifdef FP_APPLE
,	queue(cFUThread_INVALID)
#endif
,	name()
,	thread(cFUThread_INVALID)
{
	if (szName != nullptr)
	{
		name = szName;
	}

	//Create the structure from the function parameters.
	cFUThreadInternalParam* params = new cFUThreadInternalParam;
	params->object = this;

	params->parameter = parameter;

	params->func = startAddress;
#if defined(WIN32)
	unsigned int ThreadId;
	thread = (HANDLE)_beginthreadex(nullptr, 0, InternalFunc, params, 0, &ThreadId);
	threadStartedSemaphore.Down();

#elif defined (FP_APPLE)
	if (MPLibraryIsLoaded())
	{
		OSStatus status = MPCreateQueue(&queue);
		if (status == noErr)
			status = MPCreateTask(&InternalFunc, params, 0, queue, &exitCode, nullptr, 0, &thread);
	}
#elif defined(LINUX) || defined(IOS) || defined(ANDROID)
	int status = pthread_create(&thread, nullptr, InternalFunc, params);
	if (status == 0) // Success
		threadStartedSemaphore.Down();
#endif
}
Example #2
0
bool wxThreadInternal::Create( wxThread *thread, unsigned int stackSize )
{
    wxASSERT_MSG( m_state == STATE_NEW && !m_tid,
                    wxT("Create()ing thread twice?") );

    if ( thread->IsDetached() )
        Detach();

    OSStatus err = noErr;
    m_thread = thread;

    if ( m_notifyQueueId == kInvalidID )
    {
        OSStatus err = MPCreateQueue( &m_notifyQueueId );
        if (err != noErr)
        {
            wxLogSysError( wxT("Can't create the thread event queue") );

            return false;
        }
    }

    m_state = STATE_NEW;

    err = MPCreateTask(
        MacThreadStart, (void*)m_thread, stackSize,
        m_notifyQueueId, &m_exitcode, 0, 0, &m_tid );

    if (err != noErr)
    {
        wxLogSysError( wxT("Can't create thread") );

        return false;
    }

    if ( m_prio != wxPRIORITY_DEFAULT )
        SetPriority( m_prio );

    return true;
}
Example #3
0
void ui_main() {
	if( data.init_done )
		return;
	data.init_done = 1;
#	if defined(NEKO_WINDOWS)
	{
		WNDCLASSEX wcl;
		HINSTANCE hinst = GetModuleHandle(NULL);
		memset(&wcl,0,sizeof(wcl));
		wcl.cbSize			= sizeof(WNDCLASSEX);
		wcl.style			= CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
		wcl.lpfnWndProc		= WindowProc;
		wcl.cbClsExtra		= 0;
		wcl.cbWndExtra		= 0;
		wcl.hInstance		= hinst;
		wcl.hIcon			= NULL;
		wcl.hCursor			= LoadCursor(NULL, IDC_ARROW);
		wcl.hbrBackground	= (HBRUSH)(COLOR_BTNFACE+1);
		wcl.lpszMenuName	= "";
		wcl.lpszClassName	= CLASS_NAME;
		wcl.hIconSm			= 0;
		RegisterClassEx(&wcl);
	}
	data.tid = GetCurrentThreadId();
	data.wnd = CreateWindow(CLASS_NAME,"",0,0,0,0,0,NULL,NULL,NULL,NULL);
#	elif defined(NEKO_MAC)
	MPCreateTask(nothing,NULL,0,0,0,0,0,NULL); // creates a MPTask that will enable Carbon MT
	data.tid = pthread_self();
	EventTypeSpec ets = { UIEvent, eCall };
	InstallEventHandler(GetApplicationEventTarget(),NewEventHandlerUPP(handleEvents),1,&ets,0,0);
#	elif defined(NEKO_LINUX)
	g_thread_init(NULL);
	gdk_threads_init();
	gtk_init(NULL,NULL);
	setlocale(LC_NUMERIC,"POSIX"); // prevent broking atof()
	data.tid = pthread_self();
	pthread_mutex_init(&data.lock,NULL);
#	endif
}
Example #4
0
int CFSThread::Create(void *pData, long lFlags)
{
	m_pData=pData;
#if defined (WIN32CE)
	m_hThread=CreateThread(NULL, 0, CFSThreadFunc, this, lFlags, &m_lThreadID);
	return (m_hThread==0);
#elif defined (WINRT)
	// Unimplemented
	FSUNUSED(pData);
	FSUNUSED(lFlags);
	return -1;
#elif defined (WIN32)
	m_hThread=(HANDLE)_beginthreadex(NULL, 0, CFSThreadFunc, this, lFlags, &m_lThreadID);
	return (m_hThread==0);
#elif defined (UNIX)
	FSUNUSED(lFlags);
	return pthread_create(&m_hThread, 0, CFSThreadFunc, this);
#elif defined (MAC)
	FSUNUSED(lFlags);
	return MPCreateTask(CFSThreadFunc, this, 512*1024, m_WaitQueue, 0, 0, 0,&m_hThread);
#endif
}
Example #5
0
thread::thread(const function0<void>& threadfunc)
    : m_joinable(true)
{
    thread_param param(threadfunc);
#if defined(BOOST_HAS_WINTHREADS)
    m_thread = reinterpret_cast<void*>(_beginthreadex(0, 0, &thread_proxy,
                                           &param, 0, &m_id));
    if (!m_thread)
        throw thread_resource_error();
#elif defined(BOOST_HAS_PTHREADS)
    int res = 0;
    res = pthread_create(&m_thread, 0, &thread_proxy, &param);
    if (res != 0)
        throw thread_resource_error();
#elif defined(BOOST_HAS_MPTASKS)
    threads::mac::detail::thread_init();
    threads::mac::detail::create_singletons();
    OSStatus lStatus = noErr;

    m_pJoinQueueID = kInvalidID;
    m_pTaskID = kInvalidID;

    lStatus = MPCreateQueue(&m_pJoinQueueID);
    if (lStatus != noErr) throw thread_resource_error();

    lStatus = MPCreateTask(&thread_proxy, &param, 0UL, m_pJoinQueueID, NULL,
        NULL, 0UL, &m_pTaskID);
    if (lStatus != noErr)
    {
        lStatus = MPDeleteQueue(m_pJoinQueueID);
        assert(lStatus == noErr);
        throw thread_resource_error();
    }
#endif
    param.wait();
}
Example #6
0
/*****************************************************
*
* DisplaySimpleWindow ( void ) 
*
* Purpose:  Called to create a new window in response to a kHICommandNew event.  Here we create a window, set up the MyMPTaskInfo structure,
*			and create an MP thread to monitor our specified directories.
*
*/
static	void	DisplaySimpleWindow( void )
{
	OSStatus				err;
	OSStatus				err1;
	WindowRef				window;
	ControlRef				control;
	MPTaskID				mpTaskID;
	MyMPTaskInfo			*mpTaskInfo;
	FSRef					fsRef;
	char					path[MAXPATHLEN];
	DialogRef				alertDialog;
	static	EventHandlerUPP	mpWindowEventHandlerUPP;
	SInt32					i			= -1;
	const EventTypeSpec	windowEvents[]	=   {
												{ kEventClassCommand, kEventCommandProcess },
												{ kEventClassMP, kEventKQueue },
												{ kEventClassWindow, kEventWindowClose }
											};
	
	err	= CreateWindowFromNib( g.mainNib, CFSTR("MainWindow"), &window );
	if ( (err != noErr) || (window == NULL) )	goto Bail;
	
	if ( mpWindowEventHandlerUPP == NULL ) mpWindowEventHandlerUPP	= NewEventHandlerUPP( MPWindowEventHandlerProc );	//  MPWindowEventHandlerProc handles events for this window
	err = InstallWindowEventHandler( window, mpWindowEventHandlerUPP, GetEventTypeCount(windowEvents), windowEvents, window, NULL );

	//  Display the directories we are going to watch in the static text fields.  In this sample we hard code the values to a few specific locations
	err = FSFindFolder( kUserDomain, kDesktopFolderType, kDontCreateFolder, &fsRef );								//  Watch the Desktop folder
	err1 = FSRefMakePath( &fsRef, (UInt8 *)path, MAXPATHLEN );
	if ( (err == noErr) && (err1 == noErr) )
		SetControlCString( window, 'STxt', ++i, path );
	
	err = FSFindFolder( kUserDomain, kDocumentsFolderType, kDontCreateFolder, &fsRef );								//  Watch the Documents folder
	err1 = FSRefMakePath( &fsRef, (UInt8 *)path, MAXPATHLEN );
	if ( (err == noErr) && (err1 == noErr) )
		SetControlCString( window, 'STxt', ++i, path );
	
	err = FSFindFolder( kUserDomain, kCurrentUserFolderType, kDontCreateFolder, &fsRef );							//  Watch the Users folder
	err1 = FSRefMakePath( &fsRef, (UInt8 *)path, MAXPATHLEN );
	if ( (err == noErr) && (err1 == noErr) )
		SetControlCString( window, 'STxt', ++i, path );
	
	mpTaskInfo	= (MyMPTaskInfo*) NewPtrClear( sizeof(MyMPTaskInfo) );
	SetWRefCon( window, (long) mpTaskInfo );
	for ( mpTaskInfo->count = 0 ; mpTaskInfo->count < kMaxFoldersToWatch ; mpTaskInfo->count++ )
	{
		GetControlCString( window, 'STxt', mpTaskInfo->count, mpTaskInfo->path[mpTaskInfo->count] );				//  This code pretty much just reads back the strings we set above
		if ( mpTaskInfo->path[mpTaskInfo->count][0] == '\0' )   break;

		//  We initialize a number of values which are not be safe to retrieve from an MP thread.
		GetControlBySigAndID( window, 'Date', mpTaskInfo->count, &mpTaskInfo->mpControlInfo[mpTaskInfo->count].dateControl );
		GetControlBySigAndID( window, 'STxt', mpTaskInfo->count, &control );
		mpTaskInfo->mpControlInfo[mpTaskInfo->count].eventTarget = GetControlEventTarget( control );
	}
	if ( mpTaskInfo->count < 1 )
	{
		DisposePtr( (Ptr) mpTaskInfo );
		goto Bail;
	}
	
	//  Create our MP thread and pass in mpTaskInfo.  MyMPTask is responsible for watching the passed in directories, and posting notifications of changes.
	err	= MPCreateTask( MyMPTask, (void *) mpTaskInfo, 0, NULL, 0, 0, kNilOptions, &mpTaskID );
	if ( err != noErr )																								//  Alert if an error occured
	{
		CreateStandardAlert( kAlertStopAlert, CFSTR("MPCreateTask returned an error! Will not create window."), NULL, NULL, &alertDialog );
		RunStandardAlert( alertDialog, NULL, NULL );
		goto Bail;
	}
	
	ShowWindow( window );

Bail:
	return;
}
static OSStatus RunOneServer(InetHost ipAddr)
	// This routine is the main line of the thread that runs
	// an HTTP server.  ipAddr is the address on which the
	// server is listening.
	//
	// The routine uses a directory whose name is the
	// dotted decimal string representation of ipAddr as the
	// root directory of the HTTP server.
{
	OSStatus 	err;
	OSStatus 	junk;
	Str255 		ipAddrString;
	FSSpec 		dirSpec;
	CInfoPBRec 	cpb;
	ServerContext *context;
	MPTaskID    junkServerThread;
	
	// Allocate a context for the preemptive thread.
	
	err = noErr;
	context = (ServerContext *) MPAllocateAligned(sizeof(*context), kMPAllocateDefaultAligned, kNilOptions);
	if (context == NULL) {
		err = memFullErr;
	}
	
	// Fill out the context.  We do this here because it needs 
	// to use services that aren't MP-safe.
	
	if (err == noErr) {
		context->ipAddr = ipAddr;
		
		// Get ipAddr as a dotted decimal Pascal string.
		OTInetHostToString(ipAddr, ((char *) ipAddrString) + 1);
		ipAddrString[0] = OTStrLength(((char *) ipAddrString) + 1);
		
		// Find the associated dirID, creating the directory
		// if necessary.

		junk = MoreProcGetCurrentProcessFSSpec(&dirSpec);
		assert(junk == noErr);
			
		(void) FSMakeFSSpec(dirSpec.vRefNum, dirSpec.parID, ipAddrString, &dirSpec);
		context->rootVRefNum = dirSpec.vRefNum;
		err = FSpGetCatInfo(&dirSpec, 0, &cpb);
		if (err == noErr && ( (cpb.hFileInfo.ioFlAttrib & (1 << 4)) != 0) ) {
			context->rootDirID = cpb.hFileInfo.ioDirID;
		} else {
			err = FSpDirCreate(&dirSpec, 0, (SInt32 *) &context->rootDirID);
		}
	}
	
	// Start a preemptive thread to run an HTTP server on the IP address.
	
	if (err == noErr) {
		err = MPCreateTask(HTTPServerProc, context, 65536, kInvalidID, NULL, NULL, kNilOptions, &junkServerThread);
		if (err == noErr) {
			context = NULL;				// it's now the task's responsibility
		}
	}
	if (context != NULL) {
		MPFree(context);
	}
	
	return err;
}
Example #8
0
static void SendFlowControlTest(void)
{
	OSStatus  err;
	OSStatus  junk;
	MPQueueID deathQueue;
	MPTaskID  rcvTask;
	MPTaskID  sndTask;

	gRcvStarted = false;
	gLookerEP = NULL;
	gQuitLooker = false;
	
	deathQueue = kInvalidID;
	err = MPCreateQueue(&deathQueue);
	if (err == noErr) {
		err = MPCreateTask(SFCRcv, NULL, 65536, deathQueue, (void *) 1, (void *) 666, kNilOptions, &rcvTask);
	}
	if (err == noErr) {
		MPLogPrintf("Waiting for receiver to start.\n");
		while ( ! gRcvStarted ) {
			printf(".");
			fflush(stdout);
		}
		MPLogPrintf("\n");
	}
	if (err == noErr) {
		err = MPCreateTask(SFCSnd, NULL, 65536, deathQueue, (void *) 2, (void *) 666, kNilOptions, &sndTask);
	}
	if (err == noErr) {
		err = MPCreateTask(SFCLooker, NULL, 65536, deathQueue, (void *) 3, (void *) 666, kNilOptions, &rcvTask);
	}
	if (err == noErr) {
		UInt32 terminatedTaskCount;
		UInt32 taskNumber;
		OSStatus taskStatus;
		UInt32 lastPrinted;
		
		lastPrinted = 0;
		terminatedTaskCount = 0;
		do {
			err = MPWaitOnQueue(deathQueue, (void **) &taskNumber, NULL, (void **) &taskStatus, kDurationImmediate);
			if (err == noErr) {
				MPLogPrintf("Task number %ld completed with status %ld.\n", taskNumber, taskStatus);
				terminatedTaskCount += 1;
			} else if (err == kMPTimeoutErr) {
				#if !TARGET_API_MAC_CARBON
					SystemTask();
				#endif
				if (TickCount() > (lastPrinted + 60)) {
					printf(".");
					fflush(stdout);
					lastPrinted = TickCount();
				}
				err = noErr;
			}
		} while ( (err == noErr) && (terminatedTaskCount < 3) );
	}
	
	// Clean up.
	
	if (deathQueue != kInvalidID) {
		junk = MPDeleteQueue(deathQueue);
		assert(junk == noErr);
	}

	printf("gLookCounter = %ld\n", gLookCounter);
	gLookCounter = 0;
	
	if (err == noErr) {
		printf("Success!\n");
	} else {
		printf("Failed with error %ld.\n", err);
	}
}