示例#1
0
文件: acl_sem.c 项目: 2202877/acl
/* Create a semaphore */
ACL_SEM *acl_sem_create2(const char *pathname, unsigned int initial_value)
{
	const char *myname = "acl_sem_create2";
	ACL_SEM *sem;

	/* Allocate sem memory */
	sem = (ACL_SEM *) acl_mymalloc(sizeof(*sem));
	if (sem == NULL) {
		acl_msg_error("%s, %s(%d): malloc error(%s)",
			__FILE__, myname, __LINE__, acl_last_serror());
		return NULL;
	}
	/* Create the semaphore, with max value 32K */
	sem->id = CreateSemaphore(NULL, initial_value, 32 * 1024, pathname);
	sem->count = initial_value;
	if (!sem->id) {
		acl_msg_error("%s, %s(%d): Couldn't create semaphore(%s)",
			__FILE__, myname, __LINE__, acl_last_serror());
		acl_myfree(sem);
		return NULL;
	}

	return sem;
}
示例#2
0
文件: wthread.cpp 项目: 376473984/pvb
int pvinit_semaphore(WSEMAPHORE *s, int cmax)
{
/* Create a semaphore with initial count=0 max. counts of cmax. */
#ifdef PVWIN32THREAD

  s->cmax = cmax;
  s->hSemaphore = CreateSemaphore( 
    NULL,   /* no security attributes */
    0,      /* initial count */
    cmax,   /* maximum count */
    NULL);  /* unnamed semaphore */

  if(s->hSemaphore == NULL) return -1; /* Check for error. */
  return 0;

#else

  s->cmax   = cmax;
  s->nready = 0;
  pvthread_mutex_init(&s->mutex, NULL);
  return 0;

#endif
}
示例#3
0
int pthread_cond_init(pthread_cond_t *cond, const void *unused) {
        REDIS_NOTUSED(unused);
        cond->waiters = 0;
        cond->was_broadcast = 0;

        InitializeCriticalSection(&cond->waiters_lock);

        cond->sema = CreateSemaphore(NULL, 0, LONG_MAX, NULL);
        if (!cond->sema) {
            errno = GetLastError();
            return -1;
        }

        cond->continue_broadcast = CreateEvent(NULL,    /* security */
                                FALSE,                  /* auto-reset */
                                FALSE,                  /* not signaled */
                                NULL);                  /* name */
        if (!cond->continue_broadcast) {
            errno = GetLastError();
            return -1;
        }

        return 0;
}
示例#4
0
DWORD WINAPI MainThread(void* pData)
{
	MAIN_THREAD_DATA_STRUCT* mtds = (MAIN_THREAD_DATA_STRUCT*)pData;
	CRIFFChunkTreeDlg* dlg = mtds->dlg;
	STREAM* source = mtds->source;

	__int64 qwPos=source->GetPos();
	dwMBNbr=0;
	LISTHEADER lh;

	source->Seek(0);
	while (!source->IsEndOfStream()) {
		source->Read(&lh,12);
		HANDLE h = CreateSemaphore(NULL, 0, 1, NULL);
		StartInsertListThread(dlg, NULL, &lh, source->GetPos() - 12, h);
		WaitForSingleObject(h, INFINITE);
        CloseHandle(h);
	}

	source->Seek(qwPos);

	delete mtds;
	return 1;
}
示例#5
0
文件: Os.c 项目: broonie/ohNet
void OsNetworkSetInterfaceChangedObserver(OsContext* aContext, InterfaceListChanged aCallback, void* aArg)
{
    InterfaceChangeObserver* icobs;
    if (NULL != aContext->iInterfaceChangeObserver) {
        return;
    }

    icobs = (InterfaceChangeObserver*)malloc(sizeof(InterfaceChangeObserver));
    if (NULL == icobs) {
        return;
    }

    icobs->iSocket = socket(AF_INET, SOCK_DGRAM, 0);
    SetSocketBlocking(icobs->iSocket);
    icobs->iEvent = WSACreateEvent();
    icobs->iShutdownEvent = WSACreateEvent();
    icobs->iCallback = aCallback;
    icobs->iArg = aArg;
    icobs->iShutdown = 0;
    icobs->iSem = CreateSemaphore(NULL, 0, INT32_MAX, NULL);
    (void)WSAEventSelect(icobs->iSocket, icobs->iEvent, FD_ADDRESS_LIST_CHANGE);
    (void)CreateThread(NULL, 16*1024, (LPTHREAD_START_ROUTINE)&interfaceChangeThread, icobs, 0, NULL);
    aContext->iInterfaceChangeObserver = icobs;
}
// -----------------------------------------------------------------------------------------
// Semaphore functions
// -----------------------------------------------------------------------------------------
WcmSemaphore_t WcmSemaphore_Create(void)
	{
#ifdef WIN32
	return CreateSemaphore(NULL, 0, 1000, NULL);
#endif
#ifdef LINUX_OR_OSX
	WcmSemaphore_t hSem;
	if ((hSem = WcmMalloc(sizeof(stWcmSemaphore_t))) == NULL)
		return NULL;
	hSem->u32Count = 0;
	if(pthread_mutex_init(&hSem->hMutex, NULL) != 0)
	{
		WcmFree(hSem);
		return NULL;
	}
	if(pthread_cond_init(&hSem->condSem, NULL) != 0)
	{
		pthread_mutex_destroy(&hSem->hMutex);
		WcmFree(hSem);
		return NULL;
	}
	return hSem;
#endif
	} /* WcmSemaphore_Create */
示例#7
0
/*
 *  ======== SemMP_create ========
 */
SemMP_Handle SemMP_create(Int key, Int count)
{
    HANDLE     mutexId;
    HANDLE     semId;
    SemMP_Obj *sem;
        TCHAR      tszKey[MAX_PATH + 1] = TEXT("");

    GT_2trace(curTrace, GT_ENTER, "SemMP_create> key: 0x%x count: %d\n", key,
            count);

    if ((sem = (SemMP_Obj *)Memory_alloc(sizeof(SemMP_Obj), NULL)) == NULL) {
        GT_0trace(curTrace, GT_7CLASS, "SemMP_create> Memory_alloc failed\n");
        return (NULL);
    }

        _stprintf(tszKey, TEXT("%d"), key);
        sem->id = CreateSemaphore(NULL, count, count, tszKey);

        GT_1trace(curTrace, GT_ENTER, "SemMP_create> semId: 0x%x\n", sem->id);

    GT_1trace(curTrace, GT_ENTER, "Leaving SemMP_create> sem[0x%x]\n", sem);

    return (sem);
}
示例#8
0
void ipcon_device_create(Device *device, const char *uid) {
	int i;
	for(i = 0; i < MAX_NUM_CALLBACKS; i++) {
		device->registered_callbacks[i] = NULL;
		device->callback_wrappers[i] = NULL;
	}

	device->uid = ipcon_base58decode(uid);
	device->ipcon = NULL;
	device->response.function_id = 0;
	device->response.length = 0;

#ifdef _WIN32
	InitializeCriticalSection(&device->write_mutex);
	// Default state for response semaphore is empty
	device->response_semaphore = CreateSemaphore(NULL, 0, 1, NULL);
#else
	pthread_mutex_init(&device->write_mutex, NULL);
	pthread_mutex_init(&device->response_mutex, NULL);
	pthread_cond_init(&device->response_cond, NULL);

	device->response_flag = false;
#endif
}
示例#9
0
  Sem::Sem(const char* const   inName,
                       const unsigned long inCount,
                       const unsigned long inMaxCount)
    : theSemaphoreHandle(0),
      theMaxCount(inMaxCount)
  {
    if (theMaxCount == 0 || theMaxCount > 0x7FFFFFFF)
    {
      theMaxCount = 0x7FFFFFFF;
    }

    theSemaphoreHandle = CreateSemaphore(NULL,
                                         inCount > theMaxCount ? theMaxCount : inCount,
                                         theMaxCount,
                                         inName);

    if (theSemaphoreHandle == NULL)
    {
      DWORD rc = GetLastError();

      if (rc == ERROR_ALREADY_EXISTS)
      {
        // semaphore is creted try to open it
        theSemaphoreHandle = OpenSemaphore(SEMAPHORE_ALL_ACCESS | SYNCHRONIZE, FALSE, inName);

        if (theSemaphoreHandle == 0)
        {
          Logger::abort("Semaphore: failed to open.");
        }
      }
      else
      {
        Logger::abort("Semaphore: failed to create.");
      }
    }
  }
/*-------------------------------------------
| Name:OS_CreateMB
| Description:
| Parameters:
| Return Type:
| Comments:
| See:
---------------------------------------------*/
void OS_CreateMB (OS_MAILBOX* pMB, OS_U8 sizeofMsg, OS_UINT maxnofMsg, void* Buffer){
   
   if(!pMB)return;


   pMB->hSemMB = CreateSemaphore (NULL,1,1,NULL);
   pMB->hEvtMB = CreateEvent(NULL,0,0,NULL);
   pMB->dwThreadId = 0;

   pMB->pData  = Buffer;
   pMB->pRead  = pMB->pData;
   pMB->pWrite = pMB->pData;

   pMB->pEnd   = pMB->pData + ((maxnofMsg-1)*sizeofMsg);

   pMB->maxnofMsg    = maxnofMsg;
   pMB->sizeofMsg    = sizeofMsg;

   pMB->r      = 0;
   pMB->w      = 0;
   pMB->size   = maxnofMsg*sizeofMsg;
   

}
示例#11
0
sys_mbox_t sys_mbox_new(int size)
{
  struct lwip_mbox *new_mbox;

  LWIP_UNUSED_ARG(size);

  new_mbox = (struct lwip_mbox*)malloc(sizeof(struct lwip_mbox));
  LWIP_ASSERT("new_mbox != NULL", new_mbox != NULL);
  if(new_mbox == NULL) {
#if LWIP_STATS
    lwip_stats.sys.mbox.err++;
#endif /* LWIP_STATS */
    return SYS_SEM_NULL;
  }
  new_mbox->sem = CreateSemaphore(0, 0, MAX_QUEUE_ENTRIES, 0);
  LWIP_ASSERT("Error creating semaphore", new_mbox->sem != NULL);
  if(new_mbox->sem == NULL) {
#if LWIP_STATS
    lwip_stats.sys.mbox.err++;
#endif /* LWIP_STATS */
    free(new_mbox);
    new_mbox = NULL;
    return SYS_SEM_NULL;
  }
  memset(&new_mbox->q_mem, 0, sizeof(u32_t)*MAX_QUEUE_ENTRIES);
  new_mbox->head = 0;
  new_mbox->tail = 0;
#if LWIP_STATS
  lwip_stats.sys.mbox.used++;
  LWIP_ASSERT("sys_mbox_new() counter overflow", lwip_stats.sys.mbox.used != 0 );
  if (lwip_stats.sys.mbox.used > lwip_stats.sys.mbox.max) {
    lwip_stats.sys.mbox.max = lwip_stats.sys.mbox.used;
  }
#endif /* LWIP_STATS */
  return new_mbox;
}
示例#12
0
/* Create a semaphore */
SDL_sem *SDL_CreateSemaphore(Uint32 initial_value)
{
	SDL_sem *sem;

	/* Allocate sem memory */
	sem = (SDL_sem *)SDL_malloc(sizeof(*sem));
	if ( sem ) {
		/* Create the semaphore, with max value 32K */
#if defined(_WIN32_WCE) && (_WIN32_WCE < 300)
		sem->id = CreateSemaphoreCE(NULL, initial_value, 32*1024, NULL);
#else
		sem->id = CreateSemaphore(NULL, initial_value, 32*1024, NULL);
#endif
		sem->count = initial_value;
		if ( ! sem->id ) {
			SDL_SetError("Couldn't create semaphore");
			SDL_free(sem);
			sem = NULL;
		}
	} else {
		SDL_OutOfMemory();
	}
	return(sem);
}
示例#13
0
文件: thread.c 项目: dmonakhov/haggle
mutex_t mutex_create(void)
{
	mutex_t m;
	
	m = (mutex_t) malloc(sizeof(struct mutex_s));

	if(m == NULL)
		return NULL;
#if defined(OS_WINDOWS)
	m->mutex = CreateSemaphore(NULL, 1, 1, NULL);

	if(m->mutex == NULL)
		goto fail_mutex;
#else
	pthread_mutex_init(&(m->mutex), NULL);
#endif

	return m;
#if defined(OS_WINDOWS)
fail_mutex:
	free(m);
	return NULL;
#endif
}
示例#14
0
int rktio_winsock_init(rktio_t *rktio)
{
  if (!winsock_sema) {
    winsock_sema = CreateSemaphore(NULL, 1, 1, NULL);
  }

  WaitForSingleObject(winsock_sema, INFINITE);

  if (!winsock_started) {
    WSADATA data;
    if (!WSAStartup(MAKEWORD(1, 1), &data)) {
      winsock_started = 1;
    } else {
      get_windows_error();
      ReleaseSemaphore(winsock_sema, 1, NULL);
      return 0;
    }
  } else
    winsock_started++;
  
  ReleaseSemaphore(winsock_sema, 1, NULL);

  return 1;
}
示例#15
0
int main (int argc, char **argv)
{

	/*** CHECK ARGUMEN VALIDATION ********/
	/* Interpret command line */
	if (argc == 2)
	{
		/* Use local address */
		if (sscanf(argv[1], "%u", &port_number) != 1)
		{
			usage();
		}
	}
	else if (argc == 3)
	{
		/* Copy address */
		if (sscanf(argv[1], "%d.%d.%d.%d", &a1, &a2, &a3, &a4) != 4)
		{
			usage();
		}
		if (sscanf(argv[2], "%u", &port_number) != 1)
		{
			usage();
		}
	}
	else
	{
		usage();
	}

	/******END ARGUMEN VALIDATION **************/
	/* Open windows connection */
	if (WSAStartup(0x0101, &w) != 0)
	{
		fprintf(stderr, "Could not open Windows connection.\n");
		exit(0);
	}

	/* Open a datagram socket */
	sd = socket(AF_INET, SOCK_DGRAM, 0);
	if (sd == INVALID_SOCKET)
	{
		fprintf(stderr, "Could not create socket.\n");
		WSACleanup();
		exit(0);
	}

	/* Clear out server struct */
	memset((void *)&server, '\0', sizeof(struct sockaddr_in));

	/* Set family and port */
	server.sin_family = AF_INET;
	server.sin_port = htons(port_number);

	/* Set address automatically if desired */
	if (argc == 2)
	{
		/* Get host name of this computer */
		gethostname(host_name, sizeof(host_name));
		hp = gethostbyname(host_name);

		/* Check for NULL pointer */
		if (hp == NULL)
		{
			fprintf(stderr, "Could not get host name.\n");
			closesocket(sd);
			WSACleanup();
			exit(0);
		}
		
		/* Assign the address */
		server.sin_addr.S_un.S_un_b.s_b1 = hp->h_addr_list[0][0];
		server.sin_addr.S_un.S_un_b.s_b2 = hp->h_addr_list[0][1];
		server.sin_addr.S_un.S_un_b.s_b3 = hp->h_addr_list[0][2];
		server.sin_addr.S_un.S_un_b.s_b4 = hp->h_addr_list[0][3];
	}
	/* Otherwise assign it manually */
	else
	{
		server.sin_addr.S_un.S_un_b.s_b1 = (unsigned char)a1;
		server.sin_addr.S_un.S_un_b.s_b2 = (unsigned char)a2;
		server.sin_addr.S_un.S_un_b.s_b3 = (unsigned char)a3;
		server.sin_addr.S_un.S_un_b.s_b4 = (unsigned char)a4;
	}

	/* Bind address to socket */
	if (bind(sd, (struct sockaddr *)&server, sizeof(struct sockaddr_in)) == -1)
	{
		fprintf(stderr, "Could not bind name to socket.\n");
		closesocket(sd);
		WSACleanup();
		exit(0);
	}

	/* Print out server information */
	printf("Binding pada %u.%u.%u.%u : %u\n", (unsigned char)server.sin_addr.S_un.S_un_b.s_b1,
											  (unsigned char)server.sin_addr.S_un.S_un_b.s_b2,
											  (unsigned char)server.sin_addr.S_un.S_un_b.s_b3,
											  (unsigned char)server.sin_addr.S_un.S_un_b.s_b4,
											  (unsigned short) port_number);
	printf("Press CTRL + C to quit\n");

	/* Loop and get data from clients */
	// Create a semaphore with initial and max counts of MAX_SEM_COUNT

    ghSemaphore = CreateSemaphore(
        NULL,           // default security attributes
        MAX_SEM_COUNT,  // initial count
        MAX_SEM_COUNT,  // maximum count
        NULL);          // unnamed semaphore

    if (ghSemaphore == NULL)
    {
        printf("CreateSemaphore error: %d\n", GetLastError());
        return 1;
    }

    // Create 2 worker threads aThread[0] for reading and sending file
    aThread[0] = CreateThread(
                 NULL,       // default security attributes
                 0,          // default stack size
                 (LPTHREAD_START_ROUTINE) ProcRcvData,
                 NULL,       // no thread function arguments
                 0,          // default creation flags
                 &ThreadID); // receive thread identifier
    //case of making thread error
    if( aThread[0] == NULL )
    {
        printf("CreateThread error: %d\n", GetLastError());
        return 1;
    }
    //aThread[1] for listening XON and XOFF
    aThread[1] = CreateThread(
                 NULL,       // default security attributes
                 0,          // default stack size
                 (LPTHREAD_START_ROUTINE) ProcWaitSignal,
                 NULL,       // no thread function arguments
                 0,          // default creation flags
                 &ThreadID); // receive thread identifier
    //case of making thread error
    if( aThread[1] == NULL )
    {
        printf("CreateThread error: %d\n", GetLastError());
        return 1;
    }

    // Wait for all threads to terminate

    WaitForMultipleObjects(THREADCOUNT, aThread, TRUE, INFINITE);

    // Close thread and semaphore handles

    for( i=0; i < THREADCOUNT; i++ )
        CloseHandle(aThread[i]);

    CloseHandle(ghSemaphore);
    return 0;
}
示例#16
0
/*** Semaphore ***/
void vlc_sem_init (vlc_sem_t *sem, unsigned value)
{
    *sem = CreateSemaphore (NULL, value, 0x7fffffff, NULL);
    if (*sem == NULL)
        abort ();
}
示例#17
0
int DIB_OpenAudio(_THIS, SDL_AudioSpec *spec)
{
	MMRESULT result;
	int i;
	WAVEFORMATEX waveformat;

	/* Initialize the wavebuf structures for closing */
	sound = NULL;
	audio_sem = NULL;
	for ( i = 0; i < NUM_BUFFERS; ++i )
		wavebuf[i].dwUser = 0xFFFF;
	mixbuf = NULL;

	/* Set basic WAVE format parameters */
	SDL_memset(&waveformat, 0, sizeof(waveformat));
	waveformat.wFormatTag = WAVE_FORMAT_PCM;

	/* Determine the audio parameters from the AudioSpec */
	switch ( spec->format & 0xFF ) {
		case 8:
			/* Unsigned 8 bit audio data */
			spec->format = AUDIO_U8;
			waveformat.wBitsPerSample = 8;
			break;
		case 16:
			/* Signed 16 bit audio data */
			spec->format = AUDIO_S16;
			waveformat.wBitsPerSample = 16;
			break;
		default:
			SDL_SetError("Unsupported audio format");
			return(-1);
	}
	waveformat.nChannels = spec->channels;
	waveformat.nSamplesPerSec = spec->freq;
	waveformat.nBlockAlign =
		waveformat.nChannels * (waveformat.wBitsPerSample/8);
	waveformat.nAvgBytesPerSec = 
		waveformat.nSamplesPerSec * waveformat.nBlockAlign;

	/* Check the buffer size -- minimum of 1/4 second (word aligned) */
	if ( spec->samples < (spec->freq/4) )
		spec->samples = ((spec->freq/4)+3)&~3;

	/* Update the fragment size as size in bytes */
	SDL_CalculateAudioSpec(spec);

	/* Open the audio device */
	result = waveOutOpen(&sound, WAVE_MAPPER, &waveformat,
			(DWORD_PTR)FillSound, (DWORD_PTR)this, CALLBACK_FUNCTION);
	if ( result != MMSYSERR_NOERROR ) {
		SetMMerror("waveOutOpen()", result);
		return(-1);
	}

#ifdef SOUND_DEBUG
	/* Check the sound device we retrieved */
	{
		WAVEOUTCAPS caps;

		result = waveOutGetDevCaps((UINT)sound, &caps, sizeof(caps));
		if ( result != MMSYSERR_NOERROR ) {
			SetMMerror("waveOutGetDevCaps()", result);
			return(-1);
		}
		printf("Audio device: %s\n", caps.szPname);
	}
#endif

	/* Create the audio buffer semaphore */
#if defined(_WIN32_WCE) && (_WIN32_WCE < 300)
	audio_sem = CreateSemaphoreCE(NULL, NUM_BUFFERS-1, NUM_BUFFERS, NULL);
#else
	audio_sem = CreateSemaphore(NULL, NUM_BUFFERS-1, NUM_BUFFERS, NULL);
#endif
	if ( audio_sem == NULL ) {
		SDL_SetError("Couldn't create semaphore");
		return(-1);
	}

	/* Create the sound buffers */
	mixbuf = (Uint8 *)SDL_malloc(NUM_BUFFERS*spec->size);
	if ( mixbuf == NULL ) {
		SDL_SetError("Out of memory");
		return(-1);
	}
	for ( i = 0; i < NUM_BUFFERS; ++i ) {
		SDL_memset(&wavebuf[i], 0, sizeof(wavebuf[i]));
		wavebuf[i].lpData = (LPSTR) &mixbuf[i*spec->size];
		wavebuf[i].dwBufferLength = spec->size;
		wavebuf[i].dwFlags = WHDR_DONE;
		result = waveOutPrepareHeader(sound, &wavebuf[i],
							sizeof(wavebuf[i]));
		if ( result != MMSYSERR_NOERROR ) {
			SetMMerror("waveOutPrepareHeader()", result);
			return(-1);
		}
	}

	/* Ready to go! */
	next_buffer = 0;
	return(0);
}
示例#18
0
Semaphore::Semaphore(U32 initialCount, U32 maximumCount)
{
   mSemaphore = CreateSemaphore(NULL, initialCount, maximumCount, NULL);
}
// Winamp calls this with mlplugin populated after the above has been called
int mlinit()
{
	static char c[512];
	char filename[512];
	HWND hWnd = NULL;

	g_hDllInstance = mlplugin.hDllInstance;
	g_hwndParent = mlplugin.hwndWinampParent;

	_Module.Init(NULL, mlplugin.hDllInstance, &LIBID_ATLLib);

	// Handle Multiple Instances
	hSem = CreateSemaphore (NULL, 1, 1,szSemName);
	if (WaitForSingleObject (hSem, 0) == WAIT_TIMEOUT) 
	{
		CloseHandle (hSem);
		return -1;
	}

    int version = WINAMP_VERSION_MAJOR( SendMessage( mlplugin.hwndWinampParent,WM_WA_IPC,0,IPC_GETVERSION) );

    // If the version is earlier than 5, we need to use a method of track play detection
    // that involves overriding the playlist editor's event handler.
    if ( version < 5 )
    {
        hWnd = GetPEWindow(mlplugin.hwndWinampParent);
        if ( hWnd != NULL )
	    {
            SetWndSubClass( hWnd, WndProcPE, &lpWndProcOldPE );
   	    }
  	    else
    		PRINTF(DEBUG_ERROR, "Gen_AudioScrobbler::mlinit", "Failed to find Winamp PE Window");
	}

    // From version 5, Winamp supplies a better way to detect track plays that goes
    // through the main window's event handler. From 5.5 the old PE method does
    // not even work any longer.
    if ( version >= 5 && mlplugin.hwndWinampParent != NULL )
    {
        SetWndSubClass( mlplugin.hwndWinampParent, WndProcParent, &lpWndProcOldParent );
    }

	if(GetModuleFileName(mlplugin.hDllInstance,filename,sizeof(filename)) == 0)
	{
		CStdString strText;
		strText.Format("An error occurred loading the AS plugin during GetModuleFileName(), the return code was %d", GetLastError());

		::MessageBox(mlplugin.hwndWinampParent, strText.c_str(), "AudioScrobbler Error", MB_OK);
		return -1;
	}

	if(!theScrobbler.StartScrobbling(mlplugin.hDllInstance, 
		mlplugin.hwndWinampParent, 
		mlplugin.hwndLibraryParent,
		filename))
		config();

	sprintf((mlplugin.description=c), "%s v%s (ML Mode)", theScrobbler.GetAppName().c_str(), theScrobbler.GetVersionString().c_str());

	return 0;
}
示例#20
0
static void os_sem_init(os_sem_t *s) 
{
     *s = CreateSemaphore(NULL, 0, 0x7FFFFFFFL, NULL);
}
/* HOLDS: main_loop_lock */
static void
g_main_poll (gint     timeout,
	     gboolean use_priority,
	     gint     priority)
{
#ifdef  G_MAIN_POLL_DEBUG
  GTimer *poll_timer;
#endif
  GPollFD *fd_array;
  GPollRec *pollrec;
  gint i;
  gint npoll;

#ifdef G_THREADS_ENABLED
#ifndef NATIVE_WIN32
  if (wake_up_pipe[0] < 0)
    {
      if (pipe (wake_up_pipe) < 0)
	g_error ("Cannot create pipe main loop wake-up: %s\n",
		 g_strerror (errno));

      wake_up_rec.fd = wake_up_pipe[0];
      wake_up_rec.events = G_IO_IN;
      g_main_add_poll_unlocked (0, &wake_up_rec);
    }
#else
  if (wake_up_semaphore == NULL)
    {
      if ((wake_up_semaphore = CreateSemaphore (NULL, 0, 100, NULL)) == NULL)
	g_error ("Cannot create wake-up semaphore: %d", GetLastError ());
      wake_up_rec.fd = (gint) wake_up_semaphore;
      wake_up_rec.events = G_IO_IN;
      g_main_add_poll_unlocked (0, &wake_up_rec);
    }
#endif
#endif
  fd_array = g_new (GPollFD, n_poll_records);
 
  pollrec = poll_records;
  i = 0;
  while (pollrec && (!use_priority || priority >= pollrec->priority))
    {
      if (pollrec->fd->events)
	{
	  fd_array[i].fd = pollrec->fd->fd;
	  /* In direct contradiction to the Unix98 spec, IRIX runs into
	   * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
	   * flags in the events field of the pollfd while it should
	   * just ignoring them. So we mask them out here.
	   */
	  fd_array[i].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
	  fd_array[i].revents = 0;
	  i++;
	}
      
      pollrec = pollrec->next;
    }
#ifdef G_THREADS_ENABLED
  poll_waiting = TRUE;
  poll_changed = FALSE;
#endif
  
  npoll = i;
  if (npoll || timeout != 0)
    {
#ifdef	G_MAIN_POLL_DEBUG
      g_print ("g_main_poll(%d) timeout: %d\r", npoll, timeout);
      poll_timer = g_timer_new ();
#endif
      
      G_UNLOCK (main_loop);
      (*poll_func) (fd_array, npoll, timeout);
      G_LOCK (main_loop);
      
#ifdef	G_MAIN_POLL_DEBUG
      g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
	       npoll,
	       timeout,
	       g_timer_elapsed (poll_timer, NULL));
      g_timer_destroy (poll_timer);
      pollrec = poll_records;
      i = 0;
      while (i < npoll)
	{
	  if (pollrec->fd->events)
	    {
	      if (fd_array[i].revents)
		{
		  g_print (" [%d:", fd_array[i].fd);
		  if (fd_array[i].revents & G_IO_IN)
		    g_print ("i");
		  if (fd_array[i].revents & G_IO_OUT)
		    g_print ("o");
		  if (fd_array[i].revents & G_IO_PRI)
		    g_print ("p");
		  if (fd_array[i].revents & G_IO_ERR)
		    g_print ("e");
		  if (fd_array[i].revents & G_IO_HUP)
		    g_print ("h");
		  if (fd_array[i].revents & G_IO_NVAL)
		    g_print ("n");
		  g_print ("]");
		}
	      i++;
	    }
	  pollrec = pollrec->next;
	}
      g_print ("\n");
#endif
    } /* if (npoll || timeout != 0) */
  
#ifdef G_THREADS_ENABLED
  if (!poll_waiting)
    {
#ifndef NATIVE_WIN32
      gchar c;
      read (wake_up_pipe[0], &c, 1);
#endif
    }
  else
    poll_waiting = FALSE;

  /* If the set of poll file descriptors changed, bail out
   * and let the main loop rerun
   */
  if (poll_changed)
    {
      g_free (fd_array);
      return;
    }
#endif

  pollrec = poll_records;
  i = 0;
  while (i < npoll)
    {
      if (pollrec->fd->events)
	{
	  pollrec->fd->revents = fd_array[i].revents;
	  i++;
	}
      pollrec = pollrec->next;
    }

  g_free (fd_array);
}
示例#22
0
int CMainDlg::startScanSubDomain(CStringArray *sArray)
{
	DWORD dwError;
	BOOL bSemaphore = FALSE;
	DWORD dwThreadId;
	HANDLE hObject = NULL;
	LONG previousCount;
	int nMaxThread;
	int nScannedCount = 0;
	CString strDomain, strIP, strHostName;

	int nTotalNum = sArray->GetSize();
	nMaxThread = m_nMaxThread;
	m_nIpScanned = 0;
	hSemaphore = CreateSemaphore(0, nMaxThread, nMaxThread, 0);
	if (!hSemaphore)
	{
		StatusTextOut(0, "Fail To Create Semaphore");
		return 0;
	}
	
	for (int i = 0; i < nTotalNum; i++)
	{
		if (bStopScan)
			break;

		strDomain = sArray->GetAt(i);
		if (GetTickCount()%10 == 0)
			StatusTextOut(0, "%s", strDomain);
		if (GetTickCount()%5 == 0)
			StatusTextOut(1, "进度: %d/%d", i, nTotalNum);
		
		ThreadParameter *lparam = new ThreadParameter;
		lparam->strDomain = strDomain;
		lparam->pThis = this;
		hObject = CreateThread(0, 0, DomainScanThread, lparam, 0, &dwThreadId);
		if (hObject)
		{
			EnterCriticalSection(&cs);
			++nScannedCount;
			++dwThreadsUsed;
			LeaveCriticalSection(&cs);
			CloseHandle(hObject);
		}
		WaitForSingleObject(hSemaphore, INFINITE);
	}
	
	while (dwThreadsUsed)
	{
		WaitForSingleObject(hSemaphore, INFINITE);
		
		if (!bStopScan)//不是强制终止的才显示
		{
			StatusTextOut(0, "仍有%d线程正在扫描...", dwThreadsUsed);
			StatusTextOut(1, "");
		}
		
		EnterCriticalSection(&cs);
		bSemaphore = ReleaseSemaphore(hSemaphore, 1, &previousCount);
		LeaveCriticalSection(&cs);
		if (!bSemaphore)
		{
			dwError = GetLastError();
			StatusTextOut(1, "Error Code: %d", dwError);
			Sleep(1000);
			break;
		}
		if (previousCount + 1 != nMaxThread)
		{
			Sleep(200);
			if (m_nIpScanned != nScannedCount)//说明还没扫描完
				continue;
		}
		break;
	}
	if ( hSemaphore )
		CloseHandle(hSemaphore);

	return 0;
}
示例#23
0
/*
 * TransferInit:  Prepare for transfer.
 */
void TransferInit(void)
{
    buf = (char *)SafeMalloc(BUFSIZE);
    hSemaphore = CreateSemaphore(NULL, 1, 1, NULL);  // Signaled initially
}
示例#24
0
ThreadQueue::ThreadQueue(unsigned int start,unsigned int max){
	semaphore=CreateSemaphore(NULL,start,max>0?max:50,NULL);
}
示例#25
0
static void test_iocp_callback(void)
{
    char temp_path[MAX_PATH];
    char filename[MAX_PATH];
    DWORD ret;
    BOOL retb;
    static const char prefix[] = "pfx";
    HANDLE hFile;
    HMODULE hmod = GetModuleHandleA("kernel32.dll");
    DWORD bytesWritten;
    const char *buffer = "12345678123456781234567812345678";
    OVERLAPPED overlapped;

    p_BindIoCompletionCallback = (void*)GetProcAddress(hmod, "BindIoCompletionCallback");
    if(!p_BindIoCompletionCallback) {
        skip("BindIoCompletionCallback not found in this DLL\n");
        return;
    }

    sem = CreateSemaphore(NULL, 0, 1, NULL);
    ok(sem != INVALID_HANDLE_VALUE, "Creating a semaphore failed\n");

    ret = GetTempPathA(MAX_PATH, temp_path);
    ok(ret != 0, "GetTempPathA error %d\n", GetLastError());
    ok(ret < MAX_PATH, "temp path should fit into MAX_PATH\n");

    ret = GetTempFileNameA(temp_path, prefix, 0, filename);
    ok(ret != 0, "GetTempFileNameA error %d\n", GetLastError());

    hFile = CreateFileA(filename, GENERIC_READ | GENERIC_WRITE, 0, NULL,
                        CREATE_ALWAYS, FILE_FLAG_RANDOM_ACCESS, 0);
    ok(hFile != INVALID_HANDLE_VALUE, "CreateFileA: error %d\n", GetLastError());

    retb = p_BindIoCompletionCallback(hFile, iocp_callback, 0);
    ok(retb == FALSE, "BindIoCompletionCallback succeeded on a file that wasn't created with FILE_FLAG_OVERLAPPED\n");
    ok(GetLastError() == ERROR_INVALID_PARAMETER, "Last error is %d\n", GetLastError());

    ret = CloseHandle(hFile);
    ok( ret, "CloseHandle: error %d\n", GetLastError());
    ret = DeleteFileA(filename);
    ok( ret, "DeleteFileA: error %d\n", GetLastError());

    hFile = CreateFileA(filename, GENERIC_READ | GENERIC_WRITE, 0, NULL,
                        CREATE_ALWAYS, FILE_FLAG_RANDOM_ACCESS | FILE_FLAG_OVERLAPPED, 0);
    ok(hFile != INVALID_HANDLE_VALUE, "CreateFileA: error %d\n", GetLastError());

    retb = p_BindIoCompletionCallback(hFile, iocp_callback, 0);
    ok(retb == TRUE, "BindIoCompletionCallback failed\n");

    memset(&overlapped, 0, sizeof(overlapped));
    retb = WriteFile(hFile, (const void *) buffer, 4, &bytesWritten, &overlapped);
    ok(retb == TRUE || GetLastError() == ERROR_IO_PENDING, "WriteFile failed, lastError = %d\n", GetLastError());

    ret = WaitForSingleObject(sem, 5000);
    ok(ret == WAIT_OBJECT_0, "Wait for the IO completion callback failed\n");
    CloseHandle(sem);

    retb = p_BindIoCompletionCallback(hFile, iocp_callback, 0);
    ok(retb == FALSE, "BindIoCompletionCallback succeeded when setting the same callback on the file again\n");
    ok(GetLastError() == ERROR_INVALID_PARAMETER, "Last error is %d\n", GetLastError());
    retb = p_BindIoCompletionCallback(hFile, NULL, 0);
    ok(retb == FALSE, "BindIoCompletionCallback succeeded when setting the callback to NULL\n");
    ok(GetLastError() == ERROR_INVALID_PARAMETER, "Last error is %d\n", GetLastError());

    ret = CloseHandle(hFile);
    ok( ret, "CloseHandle: error %d\n", GetLastError());
    ret = DeleteFileA(filename);
    ok( ret, "DeleteFileA: error %d\n", GetLastError());

    /* win2k3 requires the Flags parameter to be zero */
    SetLastError(0xdeadbeef);
    hFile = CreateFileA(filename, GENERIC_READ | GENERIC_WRITE, 0, NULL,
                        CREATE_ALWAYS, FILE_FLAG_RANDOM_ACCESS | FILE_FLAG_OVERLAPPED, 0);
    ok(hFile != INVALID_HANDLE_VALUE, "CreateFileA: error %d\n", GetLastError());
    retb = p_BindIoCompletionCallback(hFile, iocp_callback, 12345);
    if (!retb)
        ok(GetLastError() == ERROR_INVALID_PARAMETER,
           "Expected ERROR_INVALID_PARAMETER, got %d\n", GetLastError());
    else
        ok(retb == TRUE, "BindIoCompletionCallback failed with Flags != 0\n");
    ret = CloseHandle(hFile);
    ok( ret, "CloseHandle: error %d\n", GetLastError());
    ret = DeleteFileA(filename);
    ok( ret, "DeleteFileA: error %d\n", GetLastError());

    retb = p_BindIoCompletionCallback(NULL, iocp_callback, 0);
    ok(retb == FALSE, "BindIoCompletionCallback succeeded on a NULL file\n");
    ok(GetLastError() == ERROR_INVALID_HANDLE ||
       GetLastError() == ERROR_INVALID_PARAMETER, /* vista */
       "Last error is %d\n", GetLastError());
}
示例#26
0
int main( void )
{
    int i = 0;
	int j, k = 1;
	dFILE *df;
        bHEAD *bh;
	dFIELD *field[2];
	char   buff[4096];
	long   l, ll;

	HANDLE hsem;
	TS_COM_PROPS tscp1;

	strncpy(buff, "abcdefg", 10);
	strncpy(buff, "abcdefg", 3);

/*	ProcessAttach();
        field[0] = "BH";
        field[1] = NULL;
        bh = IndexBuild("lz0.dbf", field, "lz0", BTREE_FOR_CLOSEDBF);
        IndexClose(bh);
	ProcessDetach();
        return  0;

	ProcessAttach();
	df = dAwake("e:\\wmtasql\\ls.dbf", DOPENPARA);
	ProcessDetach();
	return  0;

	get1rec(df);
        dbtFromFile(df, 1, "e:\\wmtasql\\debug\\a1");
	put_fld(df, 0, "1");
	putrec(df);

	get1rec(df);
	dbtFromFile(df, 1, "e:\\wmtasql\\debug\\a2");
	put_fld(df, 0, "2");
	putrec(df);

	get1rec(df);
	dbtFromFile(df, 1, "e:\\wmtasql\\debug\\a3");
	put_fld(df, 0, "3");
	putrec(df);

	dseek(df, 0, dSEEK_SET);
	get1rec(df);
	dbtFromFile(df, 1, "e:\\wmtasql\\debug\\aa.c");
	put_fld(df, 0, "2");
	put1rec(df);
	dbtToFile(df, 1, "e:\\wmtasql\\debug\\bb.c");
	dclose(df);
	return  2;*/

	/*strcpy(field[0].field,"ABCDEFGHIJKLMNOPQRSTUVWXYZ");
	field[0].fieldtype = 'C';
	field[0].fieldlen = 10;
	field[0].fielddec = 0;
	field[1].field[0] = '\0';

	hBuildCodeLib( "d:\\code\\code.dbf" );
	//return 0;
*/
/*	ProcessAttach();
	df = dopen("e:\\wmtasql\\ls.dbf", DOPENPARA);
	dseek(df, 10, dSEEK_SET);
	RecDelete(df);
	dseek(df, 18, dSEEK_SET);
	RecDelete(df);
	dpack(df);
	dclose(df);
	ProcessDetach();
	return  0;

*/

	tscp1.packetType = 'Q';
	tscp1.msgType = 'Q';
	tscp1.len = strlen("lz0.dbf");
	tscp1.lp = cmTS_OPEN_DBF;

	memcpy(buff, &tscp1, sizeof(TS_COM_PROPS));
	memcpy(buff+sizeof(TS_COM_PROPS), "lz0.dbf", 8);

	justRunASQL(buff, buff, 4096);

	ll = l = ((TS_COM_PROPS *)buff)->lp;

	tscp1.packetType = 'Q';
	tscp1.msgType = 'Q';
	tscp1.len = 8;
	tscp1.lp = cmTS_REC_FETCH;
	memcpy(buff, &tscp1, sizeof(TS_COM_PROPS));
	memcpy(buff+sizeof(TS_COM_PROPS), &l, 4);
	l = 1;
	memcpy(buff+sizeof(TS_COM_PROPS)+4, &l, 4);

	justRunASQL(buff, buff, 4096);

	tscp1.packetType = 'Q';
	tscp1.msgType = 'Q';
	tscp1.len = 8;
	tscp1.lp = cmTS_CLOSE_DBF;
	memcpy(buff, &tscp1, sizeof(TS_COM_PROPS));
	memcpy(buff+sizeof(TS_COM_PROPS), &ll, 4);
	justRunASQL(buff, buff, 4096);

	return  0;
	buf[0] = "thread0 ";
	buf[1] = "thread1 ";
	buf[2] = "thread2 ";
	buf[3] = "thread3 ";
	buf[4] = "thread4 ";
	buf[5] = "thread5 ";
	buf[6] = "thread6 ";


	ProcessAttach();
	printf("init success\n");

	hsem = CreateSemaphore(NULL, 1, 1, NULL);
	j = wmtAskQS(1234, "Tgask", AsqlExprInFile|Asql_USEENV, &asqlEnv, NULL, NULL, buff, 255, hsem);
	if( j >= asqlTaskThreadNum )
		printf("no thread to service\n");
	else
		printf("thread %d is servicing\n", j);
	

    {
	MSG msg1;

	while( 1 ) {
	    GetMessage(&msg1, NULL, 0, 65535);
	    printf("message received: %d\n", msg1.message);
	    if( msg1.message == ASQL_ENDTASK_MSG ) {
		break;
	    }
	}
	ReleaseSemaphore(hsem, 1, NULL);
    }
    CloseHandle(hsem);

	printf("asql finish. return value %s", buff);
	
	ProcessDetach();
	return  0;

}
示例#27
0
static void test_signalandwait(void)
{
    DWORD (WINAPI *pSignalObjectAndWait)(HANDLE, HANDLE, DWORD, BOOL);
    HMODULE kernel32;
    DWORD r;
    int i;
    HANDLE event[2], maxevents[MAXIMUM_WAIT_OBJECTS], semaphore[2], file;

    kernel32 = GetModuleHandle("kernel32");
    pSignalObjectAndWait = (void*) GetProcAddress(kernel32, "SignalObjectAndWait");

    if (!pSignalObjectAndWait)
        return;

    /* invalid parameters */
    r = pSignalObjectAndWait(NULL, NULL, 0, 0);
    if (r == ERROR_INVALID_FUNCTION)
    {
        skip("SignalObjectAndWait is not implemented\n");
        return; /* Win98/ME */
    }
    ok( r == WAIT_FAILED, "should fail\n");

    event[0] = CreateEvent(NULL, 0, 0, NULL);
    event[1] = CreateEvent(NULL, 1, 1, NULL);

    ok( event[0] && event[1], "failed to create event flags\n");

    r = pSignalObjectAndWait(event[0], NULL, 0, FALSE);
    ok( r == WAIT_FAILED, "should fail\n");

    r = pSignalObjectAndWait(NULL, event[0], 0, FALSE);
    ok( r == WAIT_FAILED, "should fail\n");


    /* valid parameters */
    r = pSignalObjectAndWait(event[0], event[1], 0, FALSE);
    ok( r == WAIT_OBJECT_0, "should succeed\n");

    /* event[0] is now signalled */
    r = pSignalObjectAndWait(event[0], event[0], 0, FALSE);
    ok( r == WAIT_OBJECT_0, "should succeed\n");

    /* event[0] is not signalled */
    r = WaitForSingleObject(event[0], 0);
    ok( r == WAIT_TIMEOUT, "event was signalled\n");

    r = pSignalObjectAndWait(event[0], event[0], 0, FALSE);
    ok( r == WAIT_OBJECT_0, "should succeed\n");

    /* clear event[1] and check for a timeout */
    ok(ResetEvent(event[1]), "failed to clear event[1]\n");
    r = pSignalObjectAndWait(event[0], event[1], 0, FALSE);
    ok( r == WAIT_TIMEOUT, "should timeout\n");

    CloseHandle(event[0]);
    CloseHandle(event[1]);

    /* create the maximum number of events and make sure 
     * we can wait on that many */
    for (i=0; i<MAXIMUM_WAIT_OBJECTS; i++)
    {
        maxevents[i] = CreateEvent(NULL, 1, 1, NULL);
        ok( maxevents[i] != 0, "should create enough events\n");
    }
    r = WaitForMultipleObjects(MAXIMUM_WAIT_OBJECTS, maxevents, 0, 0);
    ok( r != WAIT_FAILED && r != WAIT_TIMEOUT, "should succeed\n");

    for (i=0; i<MAXIMUM_WAIT_OBJECTS; i++)
        if (maxevents[i]) CloseHandle(maxevents[i]);

    /* semaphores */
    semaphore[0] = CreateSemaphore( NULL, 0, 1, NULL );
    semaphore[1] = CreateSemaphore( NULL, 1, 1, NULL );
    ok( semaphore[0] && semaphore[1], "failed to create semaphore\n");

    r = pSignalObjectAndWait(semaphore[0], semaphore[1], 0, FALSE);
    ok( r == WAIT_OBJECT_0, "should succeed\n");

    r = pSignalObjectAndWait(semaphore[0], semaphore[1], 0, FALSE);
    ok( r == WAIT_FAILED, "should fail\n");

    r = ReleaseSemaphore(semaphore[0],1,NULL);
    ok( r == FALSE, "should fail\n");

    r = ReleaseSemaphore(semaphore[1],1,NULL);
    ok( r == TRUE, "should succeed\n");

    CloseHandle(semaphore[0]);
    CloseHandle(semaphore[1]);

    /* try a registry key */
    file = CreateFile("x", GENERIC_READ|GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 
        FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE, NULL);
    r = pSignalObjectAndWait(file, file, 0, FALSE);
    ok( r == WAIT_FAILED, "should fail\n");
    ok( ERROR_INVALID_HANDLE == GetLastError(), "should return invalid handle error\n");
    CloseHandle(file);
}
// file: kernelfile.cpp
// author: Aleksandar Abu-Samra

#include "kernelfile.h"

#include "semaphores.h"
#include "drive.h"
#include "rootcluster.h"
#include "datacluster.h"

HANDLE partitionAccessMutex = CreateSemaphore(NULL, 1, 32, NULL);
HANDLE numOfFilesMutex = CreateSemaphore(NULL, 1, 32, NULL);

KernelFile::KernelFile(char *fname, char mode, Entry entry, Drive *drive) {
	strcpy(this->fname, fname);
	this->mode = mode;
	this->entry = entry;
	this->drive = drive;

	cluster = new DataCluster(drive);

	switch (mode) {
		case 'r': pointer = 0;
			break;
		case 'w': pointer = 0;
			truncate();
			break;
		case 'a': pointer = entry.size;
			seek(pointer);
			break;
	}
示例#29
0
Thread::Thread() : mRunning(true)
{
    mThreadHnd = CreateThread(0, 0, ThreadFunction, this, 0, 0);
    mSemaphore = CreateSemaphore(0, 0, 0xFFFF, 0);
}
示例#30
0
//
//  COutputQueue Constructor :
//
//  Determines if a thread is to be created and creates resources
//
//     pInputPin  - the downstream input pin we're queueing samples to
//
//     phr        - changed to a failure code if this function fails
//                  (otherwise unchanges)
//
//     bAuto      - Ask pInputPin if it can block in Receive by calling
//                  its ReceiveCanBlock method and create a thread if
//                  it can block, otherwise not.
//
//     bQueue     - if bAuto == FALSE then we create a thread if and only
//                  if bQueue == TRUE
//
//     lBatchSize - work in batches of lBatchSize
//
//     bBatchEact - Use exact batch sizes so don't send until the
//                  batch is full or SendAnyway() is called
//
//     lListSize  - If we create a thread make the list of samples queued
//                  to the thread have this size cache
//
//     dwPriority - If we create a thread set its priority to this
//
COutputQueue::COutputQueue(
             IPin         *pInputPin,          //  Pin to send stuff to
             __inout HRESULT      *phr,        //  'Return code'
             BOOL          bAuto,              //  Ask pin if queue or not
             BOOL          bQueue,             //  Send through queue
             LONG          lBatchSize,         //  Batch
             BOOL          bBatchExact,        //  Batch exactly to BatchSize
             LONG          lListSize,
             DWORD         dwPriority,
             bool          bFlushingOpt        // flushing optimization
            ) : m_lBatchSize(lBatchSize),
                m_bBatchExact(bBatchExact && (lBatchSize > 1)),
                m_hThread(NULL),
                m_hSem(NULL),
                m_List(NULL),
                m_pPin(pInputPin),
                m_ppSamples(NULL),
                m_lWaiting(0),
                m_evFlushComplete(FALSE, phr),
                m_pInputPin(NULL),
                m_bSendAnyway(FALSE),
                m_nBatched(0),
                m_bFlushing(FALSE),
                m_bFlushed(TRUE),
                m_bFlushingOpt(bFlushingOpt),
                m_bTerminate(FALSE),
                m_hEventPop(NULL),
                m_hr(S_OK)
{
    ASSERT(m_lBatchSize > 0);


    if (FAILED(*phr)) {
        return;
    }

    //  Check the input pin is OK and cache its IMemInputPin interface

    *phr = pInputPin->QueryInterface(IID_IMemInputPin, (void **)&m_pInputPin);
    if (FAILED(*phr)) {
        return;
    }

    // See if we should ask the downstream pin

    if (bAuto) {
        HRESULT hr = m_pInputPin->ReceiveCanBlock();
        if (SUCCEEDED(hr)) {
            bQueue = hr == S_OK;
        }
    }

    //  Create our sample batch

    m_ppSamples = new PMEDIASAMPLE[m_lBatchSize];
    if (m_ppSamples == NULL) {
        *phr = E_OUTOFMEMORY;
        return;
    }

    //  If we're queueing allocate resources

    if (bQueue) {
        DbgLog((LOG_TRACE, 2, TEXT("Creating thread for output pin")));
        m_hSem = CreateSemaphore(NULL, 0, 0x7FFFFFFF, NULL);
        if (m_hSem == NULL) {
            DWORD dwError = GetLastError();
            *phr = AmHresultFromWin32(dwError);
            return;
        }
        m_List = new CSampleList(NAME("Sample Queue List"),
                                 lListSize,
                                 FALSE         // No lock
                                );
        if (m_List == NULL) {
            *phr = E_OUTOFMEMORY;
            return;
        }


        DWORD dwThreadId;
        m_hThread = CreateThread(NULL,
                                 0,
                                 InitialThreadProc,
                                 (LPVOID)this,
                                 0,
                                 &dwThreadId);
        if (m_hThread == NULL) {
            DWORD dwError = GetLastError();
            *phr = AmHresultFromWin32(dwError);
            return;
        }
        SetThreadPriority(m_hThread, dwPriority);
    } else {
        DbgLog((LOG_TRACE, 2, TEXT("Calling input pin directly - no thread")));
    }
}