This is nonBusyMutex.c in view mode; [Download] [Up]
// ------------------------------------------------------------------------------------- // nonBusyMutex.c // Non-busy mutex_lock // ------------------------------------------------------------------------------------- // Permission is granted to freely redistribute this source code, and to use fragments // of this code in your own applications if you find them to be useful. This class/module, // along with the source code, come with no warranty of any kind, and the user assumes // all responsibility for its use. // ------------------------------------------------------------------------------------- #import <stdlib.h> #import <mach/cthreads.h> #import "nonBusyMutex.h" #import "threadStdio.h" // ------------------------------------------------------------------------------------- // normal mutex mode if TRUE int _nb_mutex_mode = 0; // ------------------------------------------------------------------------------------- /* mutex_init() */ void nb_mutex_init(nb_mutex_t n) { mutex_init(&n->m); condition_init(&n->c); n->l = 0; } /* mutex_alloc() */ nb_mutex_t nb_mutex_alloc() { nb_mutex_t n = ((nb_mutex_t)malloc(sizeof(struct nb_mutex_s))); nb_mutex_init(n); return n; } /* mutex_clear() */ void nb_mutex_clear(nb_mutex_t n) { mutex_clear(&n->m); condition_clear(&n->c); } /* mutex_free() */ void nb_mutex_free(nb_mutex_t n) { mutex_clear(&n->m); condition_clear(&n->c); free(n); } /* mutex_try_lock() */ int nb_mutex_try_lock(nb_mutex_t n) { int success; if (_nb_mutex_mode) return mutex_try_lock(&n->m); mutex_lock(&n->m); success = n->l? 0 : (n->l = 1); mutex_unlock(&n->m); return success; } /* mutex_lock() */ void nb_mutex_lock(nb_mutex_t n) { if (_nb_mutex_mode) { mutex_lock(&n->m); return; } mutex_lock(&n->m); while (n->l) condition_wait(&n->c, &n->m); n->l = 1; mutex_unlock(&n->m); } /* mutex_unlock() */ void nb_mutex_unlock(nb_mutex_t n) { if (_nb_mutex_mode) { mutex_unlock(&n->m); return; } mutex_lock(&n->m); n->l = 0; mutex_unlock(&n->m); condition_broadcast(&n->c); } /* mutex_name() */ char *nb_mutex_name(nb_mutex_t n) { return mutex_name(&n->m); } /* mutex_set_name() */ void nb_mutex_set_name(nb_mutex_t n, char *name) { mutex_set_name(&n->m, name); } // ------------------------------------------------------------------------------------- // conditions /* condition_wait() */ void nb_condition_wait(condition_t c, nb_mutex_t n) { if (_nb_mutex_mode) { condition_wait(c, &n->m); return; } mutex_lock(&n->m); n->l = 0; condition_broadcast(&n->c); condition_wait(c, &n->m); n->l = 1; mutex_unlock(&n->m); }
These are the contents of the former NiCE NeXT User Group NeXTSTEP/OpenStep software archive, currently hosted by Netfuture.ch.