intptr_t dispatch_semaphore_init(j9sem_t s, int initValue) { dispatch_semaphore_t *sem = (dispatch_semaphore_t *)s; *sem = dispatch_semaphore_create(initValue); return 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 {
int smb_gss_get_cred_list(struct smb_gss_cred_list **list, gss_OID mech) { struct cred_iter_ctx ctx; ctx.s = dispatch_semaphore_create(0); if (ctx.s == NULL) return ENOMEM; ctx.clist = malloc(sizeof (struct smb_gss_cred_list)); if (ctx.clist == NULL) { dispatch_release(ctx.s); return ENOMEM; } TAILQ_INIT(ctx.clist); gss_iter_creds_f(NULL, 0, mech, &ctx, cred_iter); dispatch_semaphore_wait(ctx.s, DISPATCH_TIME_FOREVER); dispatch_release(ctx.s); *list = ctx.clist; return 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); });
void SDMMD_USBMuxListenerSend(SDMMD_USBMuxListenerRef listener, struct USBMuxPacket **packet) { listener->ivars.semaphore = dispatch_semaphore_create(0x0); SDMMD_USBMuxSend(listener->ivars.socket, *packet); dispatch_semaphore_wait(listener->ivars.semaphore, (*packet)->timeout); CFMutableArrayRef updateWithRemove = CFArrayCreateMutableCopy(kCFAllocatorDefault, 0x0, listener->ivars.responses); struct USBMuxPacket *responsePacket = NULL; uint32_t removeCounter = 0x0; for (uint32_t i = 0x0; i < CFArrayGetCount(listener->ivars.responses); i++) { struct USBMuxPacket *response = (struct USBMuxPacket *)CFArrayGetValueAtIndex(listener->ivars.responses, i); if ((*packet)->body.tag == response->body.tag) { responsePacket = response; CFArrayRemoveValueAtIndex(updateWithRemove, i-removeCounter); removeCounter++; } } CFSafeRelease(listener->ivars.responses); listener->ivars.responses = CFArrayCreateMutableCopy(kCFAllocatorDefault, 0x0, updateWithRemove); CFSafeRelease(updateWithRemove); USBMuxPacketRelease(*packet); if (!responsePacket) { responsePacket = (struct USBMuxPacket *)calloc(0x1, sizeof(struct USBMuxPacket)); } *packet = responsePacket; dispatch_release(listener->ivars.semaphore); }
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); });
bool SemHelper::create(int initcount) { if (initcount < 0) { initcount = 0; } #ifdef WIN32 if (initcount > 64) { return false; } _hSem = CreateSemaphore(NULL, initcount, 64, NULL); if (_hSem == NULL) { return false; } #elif defined(__APPLE__) _semid = dispatch_semaphore_create(initcount); if (!_semid) { return false; } #else if (sem_init(&_semid, 0, initcount) != 0) { return false; } _isCreate = true; #endif return true; }
void SignalSafeSemaphore::init() { semaphore = dispatch_semaphore_create(0); if (!semaphore) // With const zero parameter this means OOM { BadAlloc::raise(); } }
ResourceHandleCFURLConnectionDelegateWithOperationQueue::ResourceHandleCFURLConnectionDelegateWithOperationQueue(ResourceHandle* handle) : ResourceHandleCFURLConnectionDelegate(handle) , m_queue(dispatch_queue_create("com.apple.WebCore/CFNetwork", DISPATCH_QUEUE_SERIAL)) , m_semaphore(dispatch_semaphore_create(0)) { dispatch_queue_t backgroundQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0); dispatch_set_target_queue(m_queue, backgroundQueue); }
bool __Platform_Red_Threading_Semaphore_Init ( __Platform_Semaphore_t & ToInit, uint32_t ResourceCount ) { ToInit = dispatch_semaphore_create ( ResourceCount ); return ToInit != NULL; }
semaphore::semaphore ( int val ) : d( new data ) { XDISPATCH_ASSERT( d.get() ); d->native = dispatch_semaphore_create( val ); XDISPATCH_ASSERT( d->native ); }
void snow_init_parallel(void* stack_top) { pthread_key_create(&state_key, finalize_thread); state_lock = dispatch_semaphore_create(1); static SnTask main_task; memset(&main_task, 0, sizeof(main_task)); main_task.stack_top = stack_top; get_state()->current_task = &main_task; }
void SDMMD_USBMuxListenerSend(SDMMD_USBMuxListenerRef listener, struct USBMuxPacket **packet) { __block struct USBMuxPacket *block_packet = *packet; dispatch_sync(listener->ivars.operationQueue, ^{ // This semaphore will be signaled when a response is received listener->ivars.semaphore = dispatch_semaphore_create(0); // Send the outgoing packet SDMMD_USBMuxSend(listener->ivars.socket, block_packet); // Wait for a response-type packet to be received dispatch_semaphore_wait(listener->ivars.semaphore, block_packet->timeout); CFMutableArrayRef updateWithRemove = CFArrayCreateMutableCopy(kCFAllocatorDefault, 0, listener->ivars.responses); // Search responses for a packet that matches the one sent struct USBMuxPacket *responsePacket = NULL; uint32_t removeCounter = 0; for (uint32_t i = 0; i < CFArrayGetCount(listener->ivars.responses); i++) { struct USBMuxPacket *response = (struct USBMuxPacket *)CFArrayGetValueAtIndex(listener->ivars.responses, i); if ((*packet)->body.tag == response->body.tag) { // Equal tags indicate response to request if (responsePacket) { // Found additional response, destroy old one USBMuxPacketRelease(responsePacket); } // Each matching packet is removed from the responses list responsePacket = response; CFArrayRemoveValueAtIndex(updateWithRemove, i - removeCounter); removeCounter++; } } if (responsePacket == NULL) { // Didn't find an appropriate response, initialize an empty packet to return responsePacket = (struct USBMuxPacket *)calloc(1, sizeof(struct USBMuxPacket)); } CFSafeRelease(listener->ivars.responses); listener->ivars.responses = CFArrayCreateMutableCopy(kCFAllocatorDefault, 0, updateWithRemove); CFSafeRelease(updateWithRemove); // Destroy sent packet USBMuxPacketRelease(block_packet); // Return response packet to caller block_packet = responsePacket; // Discard "waiting for response" semaphore dispatch_release(listener->ivars.semaphore); });
static int smb_acquire_cred(const char *user, const char *domain, const char *password, gss_OID mech, void **gssCreds) { gss_auth_identity_desc identity; struct smb_gss_cred_ctx aq_cred_ctx; uint32_t maj = !GSS_S_COMPLETE; if (password == NULL || user == NULL || *user == '\0') return 0; identity.type = GSS_AUTH_IDENTITY_TYPE_1; identity.flags = 0; identity.username = strdup(user); identity.realm = strdup(domain ? domain : ""); identity.password = strdup(password); identity.credentialsRef = NULL; if (identity.username == NULL || identity.realm == NULL || identity.password == NULL) goto out; aq_cred_ctx.sem = dispatch_semaphore_create(0); if (aq_cred_ctx.sem == NULL) goto out; maj = gss_acquire_cred_ex_f(NULL, GSS_C_NO_NAME, 0, GSS_C_INDEFINITE, mech, GSS_C_INITIATE, &identity, &aq_cred_ctx, acquire_cred_complete); if (maj == GSS_S_COMPLETE) { dispatch_semaphore_wait(aq_cred_ctx.sem, DISPATCH_TIME_FOREVER); maj = aq_cred_ctx.maj; *gssCreds = aq_cred_ctx.creds; } if (maj != GSS_S_COMPLETE) smb_log_info("Acquiring NTLM creds for %s\%s failed. GSS returned %d", ASL_LEVEL_INFO, domain, user, maj); dispatch_release(aq_cred_ctx.sem); out: free(identity.username); free(identity.realm); free(identity.password); return (maj == GSS_S_COMPLETE); }
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); });
static VALUE rb_semaphore_init(VALUE self, SEL sel, VALUE value) { dispatch_semaphore_t s = dispatch_semaphore_create(NUM2LONG(value)); if (s == NULL) { rb_raise(rb_eArgError, "Can't create semaphore based on value `%ld'", NUM2LONG(value)); } RSemaphore(self)->sem = s; RSemaphore(self)->count = NUM2LONG(value); return self; }
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); });
// CONSTRUCTOR //------------------------------------------------------------------------------ Semaphore::Semaphore() { #if defined( __WINDOWS__ ) m_Semaphore = CreateSemaphore( nullptr, 0, 0x7FFFFFFF, nullptr ); ASSERT( m_Semaphore ); #elif defined( __APPLE__ ) m_Semaphore = dispatch_semaphore_create(0); ASSERT( m_Semaphore ); #elif defined( __LINUX__ ) VERIFY( sem_init( &m_Semaphore, 0, 0 ) == 0 ); #endif }
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); });
int main() { fprintf(stderr, "Hello world.\n"); dispatch_semaphore_t done = dispatch_semaphore_create(0); barrier_init(&barrier, 2); dispatch_queue_t q = dispatch_queue_create("my.queue", DISPATCH_QUEUE_CONCURRENT); dispatch_queue_t bgq = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_async(bgq, ^{ dispatch_sync(q, ^{ global = 42; }); barrier_wait(&barrier); });
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); });
heim_isemaphore heim_ipc_semaphore_create(long value) { #ifdef HAVE_GCD return (heim_isemaphore)dispatch_semaphore_create(value); #elif !defined(ENABLE_PTHREAD_SUPPORT) heim_assert(0, "no semaphore support w/o pthreads"); return NULL; #else heim_isemaphore s = malloc(sizeof(*s)); if (s == NULL) return NULL; HEIMDAL_MUTEX_init(&s->mutex); pthread_cond_init(&s->cond, NULL); s->counter = value; return s; #endif }
static OSStatus sendTSARequestWithXPC(const unsigned char *tsaReq, size_t tsaReqLength, const unsigned char *tsaURL, unsigned char **tsaResp, size_t *tsaRespLength) { __block OSStatus result = noErr; int timeoutInSeconds = 15; extern xpc_object_t xpc_create_with_format(const char * format, ...); dispatch_queue_t xpc_queue = dispatch_queue_create("com.apple.security.XPCTimeStampingService", DISPATCH_QUEUE_SERIAL); __block dispatch_semaphore_t waitSemaphore = dispatch_semaphore_create(0); dispatch_time_t finishTime = dispatch_time(DISPATCH_TIME_NOW, timeoutInSeconds * NSEC_PER_SEC); xpc_connection_t con = xpc_connection_create("com.apple.security.XPCTimeStampingService", xpc_queue); xpc_connection_set_event_handler(con, ^(xpc_object_t event) { xpc_type_t xtype = xpc_get_type(event); if (XPC_TYPE_ERROR == xtype) { tsaDebug("default: connection error: %s\n", xpc_dictionary_get_string(event, XPC_ERROR_KEY_DESCRIPTION)); } else { tsaDebug("default: unexpected connection event %p\n", event); } });
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); });
int main(int argc, const char *argv[]) { done = dispatch_semaphore_create(0); dispatch_queue_t queue = dispatch_queue_create("my.queue", DISPATCH_QUEUE_CONCURRENT); dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL, SIGHUP, 0, queue); global = 42; dispatch_source_set_registration_handler_f(source, handler); dispatch_resume(source); dispatch_semaphore_wait(done, DISPATCH_TIME_FOREVER); return 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; }
Error Sem::create(KDuint value, Sem **returnValue) { const long lvalue = static_cast<long>(value); if (lvalue < 0) { *returnValue = nullptr; return Error(KD_EINVAL); } const dispatch_semaphore_t dispatch = dispatch_semaphore_create(lvalue); if (dispatch == nullptr) { *returnValue = nullptr; return Error(KD_ENOSPC); } Sem *sem = new Sem; sem->mNativeSem.dispatch = dispatch; sem->mNativeSem.value = lvalue; *returnValue = sem; return Error(0); }
void OSXMakeQueue(platform_work_queue* Queue, uint32 ThreadCount) { Queue->CompletionGoal = 0; Queue->CompletionCount = 0; Queue->NextEntryToWrite = 0; Queue->NextEntryToRead = 0; Queue->SemaphoreHandle = dispatch_semaphore_create(0); for (uint32 ThreadIndex = 0; ThreadIndex < ThreadCount; ++ThreadIndex) { pthread_t ThreadId; int r = pthread_create(&ThreadId, NULL, OSXQueueThreadProc, Queue); if (r != 0) { printf("Error creating thread %d\n", ThreadIndex); } } }
* @file * vuo.test.delay node implementation. * * @copyright Copyright © 2012–2014 Kosada Incorporated. * This code may be modified and distributed under the terms of the GNU Lesser General Public License (LGPL) version 2 or later. * For more information, see http://vuo.org/license. */ #include "node.h" #include <dispatch/dispatch.h> VuoModuleMetadata({ "title" : "Delay", "description" : "", "version" : "1.0.0", "node": { "isInterface" : false } }); void nodeEvent ( VuoInputData(VuoReal, {"default":1,"suggestedMin":0,"suggestedStep":0.1}) seconds, VuoOutputEvent() event ) { dispatch_semaphore_t temporaryDeadlock = dispatch_semaphore_create(0); dispatch_semaphore_wait(temporaryDeadlock, dispatch_time(DISPATCH_TIME_NOW, seconds * NSEC_PER_SEC)); }