Example #1
0
CAMLprim value
caml_init_vmnet(value v_mode)
{
  CAMLparam1(v_mode);
  CAMLlocal3(v_iface_ref,v_res,v_mac);
  xpc_object_t interface_desc = xpc_dictionary_create(NULL, NULL, 0);
  xpc_dictionary_set_uint64(interface_desc, vmnet_operation_mode_key, Int_val(v_mode));
  uuid_t uuid;
  uuid_generate_random(uuid);
  xpc_dictionary_set_uuid(interface_desc, vmnet_interface_id_key, uuid);
  __block interface_ref iface = NULL;
  __block vmnet_return_t iface_status = 0;
  __block unsigned char *mac = malloc(6);
  if (!mac) caml_raise_out_of_memory ();
  __block unsigned int mtu = 0;
  __block unsigned int max_packet_size = 0;
  dispatch_queue_t if_create_q = dispatch_queue_create("org.openmirage.vmnet.create", DISPATCH_QUEUE_SERIAL);
  dispatch_semaphore_t iface_created = dispatch_semaphore_create(0);
  iface = vmnet_start_interface(interface_desc, if_create_q,
    ^(vmnet_return_t status, xpc_object_t interface_param) { 
      iface_status = status;
      if (status != VMNET_SUCCESS || !interface_param) {
         dispatch_semaphore_signal(iface_created);
         return;
      }
      //printf("mac desc: %s\n", xpc_copy_description(xpc_dictionary_get_value(interface_param, vmnet_mac_address_key)));
      const char *macStr = xpc_dictionary_get_string(interface_param, vmnet_mac_address_key);
      unsigned char lmac[6];
      if (sscanf(macStr, "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx", &lmac[0], &lmac[1], &lmac[2], &lmac[3], &lmac[4], &lmac[5]) != 6)
        errx(1, "Unexpected MAC address received from vmnet");
      memcpy(mac, lmac, 6);
      mtu = xpc_dictionary_get_uint64(interface_param, vmnet_mtu_key);
      max_packet_size = xpc_dictionary_get_uint64(interface_param, vmnet_max_packet_size_key);
      dispatch_semaphore_signal(iface_created);
    });
Example #2
0
void OSXAddEntry(platform_work_queue* Queue, platform_work_queue_callback* Callback, void* Data)
{
    // TODO(casey): Switch to InterlockedCompareExchange eventually
    // so that any thread can add?
    uint32 NewNextEntryToWrite = (Queue->NextEntryToWrite + 1) % ArrayCount(Queue->Entries);
    Assert(NewNextEntryToWrite != Queue->NextEntryToRead);
    platform_work_queue_entry *Entry = Queue->Entries + Queue->NextEntryToWrite;
    Entry->Callback = Callback;
    Entry->Data = Data;
    ++Queue->CompletionGoal;
    OSMemoryBarrier();
    // Not needed: _mm_sfence();
    Queue->NextEntryToWrite = NewNextEntryToWrite;
	dispatch_semaphore_signal(Queue->SemaphoreHandle);

#if 0
	int r = dispatch_semaphore_signal(Queue->SemaphoreHandle);
	if (r > 0)
	{
		printf("  dispatch_semaphore_signal: A thread was woken\n");
	}
	else
	{
		printf("  dispatch_semaphore_signal: No thread was woken\n");
	}
#endif
}
Example #3
0
static void finalize_thread(void* _state) {
	SnDispatchThreadState* s = (SnDispatchThreadState*)_state;
	dispatch_semaphore_signal(s->gc_barrier); // when finalizing a thread during gc, we don't want to wait for this.
	dispatch_semaphore_wait(state_lock, DISPATCH_TIME_FOREVER);
	if (s->next) s->next->previous = s->previous;
	if (s->previous) s->previous->next = s->next;
	state = s->next;
	dispatch_semaphore_signal(state_lock);
	dispatch_release(s->gc_barrier);
	snow_free(s);
}
Example #4
0
void *consumerFunc(void * arg)          // 消费者线程
{
    while(true)
    {
        dispatch_semaphore_wait(full, DISPATCH_TIME_FOREVER);
        dispatch_semaphore_wait(mutex, DISPATCH_TIME_FOREVER);
        remove_item();
        print_items();
        dispatch_semaphore_signal(mutex);
        dispatch_semaphore_signal(empty);
        sleep(5);
    }
}
Example #5
0
static void
rb_semaphore_finalize(void *rcv, SEL sel)
{
    if (RSemaphore(rcv)->sem != NULL) {
	while (dispatch_semaphore_signal(RSemaphore(rcv)->sem) != 0) {}
	while (--RSemaphore(rcv)->count >= 0) {
	    dispatch_semaphore_signal(RSemaphore(rcv)->sem);
	}
	dispatch_release(RSemaphore(rcv)->sem);
    }
    if (rb_semaphore_finalize_super != NULL) {
        ((void(*)(void *, SEL))rb_semaphore_finalize_super)(rcv, sel);
    }
}
Example #6
0
void *producerFunc(void *arg)           // 生产者线程
{
    int item;
    while(true)
    {
        dispatch_semaphore_wait(empty, DISPATCH_TIME_FOREVER);
        dispatch_semaphore_wait(mutex, DISPATCH_TIME_FOREVER);
        item = product_NO++;
        insert_item(item);
        print_items();
        dispatch_semaphore_signal(mutex);
        dispatch_semaphore_signal(full);
        sleep(3);
    }
}
Example #7
0
File: timer.c Project: aosm/Heimdal
static void
trigger_jobs(void)
{
    time_t now = time(NULL);

    while (1) {
	struct heim_event_data *e = rk_UNCONST(heap_head(timer_heap));

	if (e != NULL && e->t < now) {
	    heap_remove_head(timer_heap);
	    e->hptr = HEAP_INVALID_PTR;

	    /* if its already running, lets retry 10s from now */
	    if (e->flags & RUNNING) {
		e->t = now + 10;
		heap_insert(timer_heap, e, &e->hptr);
		continue;
	    }
	    e->flags |= RUNNING;

	    _heim_ipc_suspend_timer();

	    dispatch_async(timer_job_q, ^{ 
		    e->callback(e, e->ctx); 
		    dispatch_async(timer_sync_q, ^{
			    e->flags &= ~RUNNING;
			    if (e->running)
				dispatch_semaphore_signal(e->running);

			    _heim_ipc_restart_timer();
			});
		});
Example #8
0
char *
Digest_File(CCDigestAlg algorithm, const char *filename, char *buf)
{
	int fd;
	__block CCDigestCtx ctx;
	dispatch_queue_t queue;
	dispatch_semaphore_t sema;
	dispatch_io_t io;
	__block int s_error = 0;

	/* dispatch_io_create_with_path requires an absolute path */
	fd = open(filename, O_RDONLY);
	if (fd < 0) {
		return NULL;
	}

	(void)fcntl(fd, F_NOCACHE, 1);

	(void)osx_assumes_zero(CCDigestInit(algorithm, &ctx));

	queue = dispatch_queue_create("com.apple.mtree.io", NULL);
	osx_assert(queue);
	sema = dispatch_semaphore_create(0);
	osx_assert(sema);

	io = dispatch_io_create(DISPATCH_IO_STREAM, fd, queue, ^(int error) {
		if (error != 0) {
			s_error = error; 
		}
		(void)close(fd);
		(void)dispatch_semaphore_signal(sema);
	});
    void
    RTMPSession::streamStatusChanged(StreamStatus_t status)
    {
        if(status & kStreamStatusConnected && m_state < kClientStateConnected) {
            setClientState(kClientStateConnected);
        }
        if(status & kStreamStatusReadBufferHasBytes) {
            dataReceived();
        }
        if(status & kStreamStatusWriteBufferHasSpace) {
            if(m_state < kClientStateHandshakeComplete) {
                handshake();
            } else {
                
#ifdef __APPLE__
                dispatch_semaphore_signal(m_networkWaitSemaphore);
#else 
                m_networkMutex.unlock();
                m_networkCond.notify_one();
#endif
            }
        }
        if(status & kStreamStatusEndStream) {
            setClientState(kClientStateNotConnected);
        }
        if(status & kStreamStatusErrorEncountered) {
            setClientState(kClientStateError);
        }
    }
Example #10
0
int main (int argc, const char * argv[]) {
	dispatch_group_t	mg = dispatch_group_create();
	dispatch_semaphore_t ds;
	__block int numRunning = 0;
	int	qWidth = 5;		
	int numWorkBlocks = 100;
	
	if (argc >= 2) {
		qWidth = atoi(argv[1]);	// use the command 1st line parameter as the queue width
		if (qWidth==0) qWidth=1; // protect against bad values
	}
	
	if (argc >=3) {
		numWorkBlocks = atoi(argv[2]);	// use the 2nd command line parameter as the queue width
		if (numWorkBlocks==0) numWorkBlocks=1; // protect against bad values
	}
	
	printf("Starting dispatch semaphore test to simulate a %d wide dispatch queue\n", qWidth );
	ds = dispatch_semaphore_create(qWidth);
	
	int i;
	for (i=0; i<numWorkBlocks; i++) {
		// synchronize the whole shebang every 25 work units...
		if (i % 25 == 24) {
			dispatch_group_async(mg,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{
				// wait for all pending work units to finish up... 
				for (int x=0; x<qWidth; x++) dispatch_semaphore_wait(ds, DISPATCH_TIME_FOREVER);
				// do the thing that is critical here
				printf("doing something critical...while %d work units are running \n",numRunning);
				// and let work continue unimpeeded
				for (int x=0; x<qWidth; x++) dispatch_semaphore_signal(ds);
			});
		} else {
Example #11
0
void __Platform_Red_Threading_Semaphore_Post ( __Platform_Semaphore_t & Target, uint32_t PostCount )
{
	
	for ( uint32_t I = 0; I < PostCount; I ++ )
		dispatch_semaphore_signal ( Target );
	
}
void ResourceHandleCFURLConnectionDelegateWithOperationQueue::releaseHandle()
{
    ResourceHandleCFURLConnectionDelegate::releaseHandle();
    m_requestResult = nullptr;
    m_cachedResponseResult = nullptr;
    m_boolResult = false;
    dispatch_semaphore_signal(m_semaphore);
}
Example #13
0
File: gss.c Project: B1NG0/cifs
static void
cred_iter(void *ctx, gss_OID moid, gss_cred_id_t cred)
{
	struct cred_iter_ctx *context = (struct cred_iter_ctx *)ctx;
	if (cred == GSS_C_NO_CREDENTIAL) {
		dispatch_semaphore_signal(context->s);
		return;
	}
	smb_gss_add_cred(context->clist, moid, cred);
}
Example #14
0
static int
vmnet_get_mac_address_from_uuid(char *guest_uuid_str) {
/*
 * from vmn_create() in https://github.com/mist64/xhyve/blob/master/src/pci_virtio_vmnet.c
 */
  xpc_object_t interface_desc;
  uuid_t uuid;
  __block interface_ref iface;
  __block vmnet_return_t iface_status;
  dispatch_semaphore_t iface_created;
  dispatch_queue_t if_create_q;
  uint32_t uuid_status;

  interface_desc = xpc_dictionary_create(NULL, NULL, 0);
  xpc_dictionary_set_uint64(interface_desc, vmnet_operation_mode_key, VMNET_SHARED_MODE);

  uuid_from_string(guest_uuid_str, &uuid, &uuid_status);
  if (uuid_status != uuid_s_ok) {
    fprintf(stderr, "Invalid UUID\n");
    return -1;
  }

  xpc_dictionary_set_uuid(interface_desc, vmnet_interface_id_key, uuid);
  iface = NULL;
  iface_status = 0;

  if_create_q = dispatch_queue_create("org.xhyve.vmnet.create", DISPATCH_QUEUE_SERIAL);

  iface_created = dispatch_semaphore_create(0);

  iface = vmnet_start_interface(interface_desc, if_create_q,
    ^(vmnet_return_t status, xpc_object_t interface_param)
  {
    iface_status = status;
    if (status != VMNET_SUCCESS || !interface_param) {
      dispatch_semaphore_signal(iface_created);
      return;
    }

    printf("%s\n", xpc_dictionary_get_string(interface_param, vmnet_mac_address_key));

    dispatch_semaphore_signal(iface_created);
  });
Example #15
0
// Signal
//------------------------------------------------------------------------------
void Semaphore::Signal()
{
    #if defined( __WINDOWS__ )
        VERIFY( ReleaseSemaphore( m_Semaphore, 1, nullptr ) );
    #elif defined( __APPLE__ )
        dispatch_semaphore_signal( m_Semaphore );
    #elif defined( __LINUX__ )
        VERIFY( sem_post( &m_Semaphore ) == 0 );
    #endif
}
Example #16
0
static void *
spinning_thread(void *semp)
{
	T_QUIET;
	T_ASSERT_NOTNULL(semp, "semaphore passed to thread should not be NULL");
	dispatch_semaphore_signal(*(dispatch_semaphore_t *)semp);

	while (running_threads);
	return NULL;
}
Example #17
0
int
OSMemoryNotificationTimedWait(OSMemoryNotificationRef note, OSMemoryNotificationLevel *level, const struct timeval *abstime)
{
    dispatch_semaphore_t sema = dispatch_semaphore_create(0);
    dispatch_retain(sema);
    
    dispatch_source_t memoryNotificationSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_VM, 0, DISPATCH_VM_PRESSURE, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0));
    dispatch_source_set_event_handler(memoryNotificationSource, ^{
        dispatch_semaphore_signal(sema);
        dispatch_release(sema);
    });
Example #18
0
bool SemHelper::post()
{
#ifdef WIN32
	return ReleaseSemaphore(_hSem, 1, NULL) ? true : false;
#elif defined(__APPLE__)
	return dispatch_semaphore_signal(_semid) == 0;
#else
	return (sem_post(&_semid) == 0);
#endif

}
Example #19
0
File: gss.c Project: B1NG0/cifs
static void
acquire_cred_complete(void *ctx, OM_uint32 maj, gss_status_id_t status __unused,
	 gss_cred_id_t creds, gss_OID_set oids, OM_uint32 time_rec __unused)
{
	uint32_t min;
	struct smb_gss_cred_ctx *aq_cred_ctx = ctx;

	gss_release_oid_set(&min, &oids);
	aq_cred_ctx->creds = creds;
	aq_cred_ctx->maj = maj;
	dispatch_semaphore_signal(aq_cred_ctx->sem);
}
Example #20
0
int main(int argc, const char *argv[]) {
  fprintf(stderr, "start\n");
  done = dispatch_semaphore_create(0);

  dispatch_queue_t q = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

  my_global = 10;
  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_MSEC)), q, ^{
    my_global = 42;

    dispatch_semaphore_signal(done);
  });
static bool clearAllKVS(CFErrorRef *error)
{
    __block bool result = false;
    const uint64_t maxTimeToWaitInSeconds = 30ull * NSEC_PER_SEC;
    dispatch_queue_t processQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_semaphore_t waitSemaphore = dispatch_semaphore_create(0);
    dispatch_time_t finishTime = dispatch_time(DISPATCH_TIME_NOW, maxTimeToWaitInSeconds);
    
    SOSCloudKeychainClearAll(processQueue, ^(CFDictionaryRef returnedValues, CFErrorRef cerror)
    {
        result = (cerror != NULL);
        dispatch_semaphore_signal(waitSemaphore);
    });
void dispatch_semaphore_blocks()
{
	static size_t total;
	dispatch_semaphore_t dsema;

    MU_BEGIN_TEST(dispatch_semaphore_blocks);

	dsema = dispatch_semaphore_create(1);
    MU_ASSERT_NOT_NULL(dsema);

	dispatch_apply(LAPS, dispatch_queue_create(0,0), ^(size_t idx) {
		dispatch_semaphore_wait(dsema, DISPATCH_TIME_FOREVER);
		total++;
		dispatch_semaphore_signal(dsema);
	});
int
main(void)
{
	static long total;
	dispatch_semaphore_t dsema;

	dispatch_test_start("Dispatch Semaphore");

	dsema = dispatch_semaphore_create(1);
	assert(dsema);

	dispatch_apply(LAPS, dispatch_get_global_queue(0, 0), ^(size_t idx __attribute__((unused))) {
		dispatch_semaphore_wait(dsema, DISPATCH_TIME_FOREVER);
		total++;
		dispatch_semaphore_signal(dsema);
	});
Example #24
0
long
heim_ipc_semaphore_signal(heim_isemaphore s)
{
#ifdef HAVE_GCD
    return dispatch_semaphore_signal((dispatch_semaphore_t)s);
#elif !defined(ENABLE_PTHREAD_SUPPORT)
    heim_assert(0, "no semaphore support w/o pthreads");
    return EINVAL;
#else
    int wakeup;
    HEIMDAL_MUTEX_lock(&s->mutex);
    wakeup = (++s->counter == 0) ;
    HEIMDAL_MUTEX_unlock(&s->mutex);
    if (wakeup)
	pthread_cond_signal(&s->cond);
    return 0;
#endif
}
Example #25
0
/*
 * pj_sem_post()
 */
PJ_DEF(pj_status_t) pj_sem_post(pj_sem_t *sem)
{
#if PJ_HAS_THREADS
    int result;
    PJ_LOG(6, (sem->obj_name, "Semaphore released by thread %s",
			      pj_thread_this(sem->inst_id)->obj_name));
#if defined(PJ_DARWINOS) && PJ_DARWINOS!=0
	result = dispatch_semaphore_signal(sem->sem);
#else
    result = sem_post( sem->sem );
#endif
    if (result == 0)
	return PJ_SUCCESS;
    else
	return PJ_RETURN_OS_ERROR(pj_get_native_os_error());
#else
    pj_assert( sem == (pj_sem_t*) 1);
    return PJ_SUCCESS;
#endif
}
Example #26
0
static SnDispatchThreadState* init_thread() {
	ASSERT(pthread_getspecific(state_key) == NULL);
	SnDispatchThreadState* s = (SnDispatchThreadState*)snow_malloc(sizeof(SnDispatchThreadState));
	s->current_task = NULL;
	s->gc_barrier = dispatch_semaphore_create(0); // starts locked
	s->previous = NULL;
	
	// prepend this state to the list of thread states
	dispatch_semaphore_wait(state_lock, DISPATCH_TIME_FOREVER);
	s->next = state;
	if (s->next) {
		ASSERT(s->next->previous == NULL);
		s->next->previous = s;
	}
	state = s;
	dispatch_semaphore_signal(state_lock);
	
	pthread_setspecific(state_key, s);
	return s;
}
Example #27
0
static void
_dispatch_apply2(void *_ctxt)
{
	struct dispatch_apply_s *da = _ctxt;
	size_t const iter = da->da_iterations;
	dispatch_function_apply_t func = da->da_func;
	void *const ctxt = da->da_ctxt;
	size_t idx;

	_dispatch_workitem_dec(); // this unit executes many items

	// Striding is the responsibility of the caller.
	while (fastpath((idx = dispatch_atomic_inc((intptr_t*)&da->da_index) - 1) < iter)) {
		func(ctxt, idx);
		_dispatch_workitem_inc();
	}

	if (dispatch_atomic_dec((intptr_t*)&da->da_thr_cnt) == 0) {
		dispatch_semaphore_signal(da->da_sema);
	}
}
Example #28
0
/*
 * 'cups_gss_acquire()' - Kerberos credentials callback.
 */
static void
cups_gss_acquire(
    void            *ctx,		/* I - Caller context */
    OM_uint32       major,		/* I - Major error code */
    gss_status_id_t status,		/* I - Status (unused) */
    gss_cred_id_t   creds,		/* I - Credentials (if any) */
    gss_OID_set     oids,		/* I - Mechanism OIDs (unused) */
    OM_uint32       time_rec)		/* I - Timestamp (unused) */
{
  uint32_t		min;		/* Minor error code */
  _cups_gss_acquire_t	*data;		/* Callback data */


  (void)status;
  (void)time_rec;

  data        = (_cups_gss_acquire_t *)ctx;
  data->major = major;
  data->creds = creds;

  gss_release_oid_set(&min, &oids);
  dispatch_semaphore_signal(data->sem);
}
Example #29
0
int gbDB_IncDecrementWithSemaphore(int*                 x,
                                   dispatch_semaphore_t sema,
                                   const bool           isInc,
                                   const bool           isDec)
{
    int retVal = -1;
    
    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
    
    if (isInc)
    {
        *x = *x + 1;
    }//if
    else if (isDec)
    {
        *x = *x - 1;
    }//else if
    
    retVal = *x;
    
    dispatch_semaphore_signal(sema);
    
    return retVal;
}//gbDB_IncDecrementWithSemaphore
Example #30
0
/* 
 *  call-seq:
 *    sema.signal => true or false
 *
 *  Signals the semaphore to wake up any waiting threads
 *
 *  Returns true if no thread is waiting, false otherwise
 *
 *     gcdq = Dispatch::Queue.new('doc')
 *     sema = Dispatch::Semaphore.new(0)
 *     gcdq.async { sleep 0.1; sema.signal } #=> false
 *     sema.wait
 *
 */
static VALUE
rb_semaphore_signal(VALUE self, SEL sel)
{
    return dispatch_semaphore_signal(RSemaphore(self)->sem) == 0 
        ? Qtrue : Qfalse;
}