int application_start( void ) { OSStatus err = kNoErr; /* Create a mutex*/ err = mico_rtos_init_mutex( &mutex); require_noerr(err, exit); /* Create threads */ err = mico_rtos_create_thread( NULL, MICO_APPLICATION_PRIORITY+1, "t1", run, 0x800, p_name1 ); require_noerr(err, exit); err = mico_rtos_create_thread( NULL, MICO_APPLICATION_PRIORITY+1, "t2", run, 0x800, p_name2 ); require_noerr(err, exit); err = mico_rtos_create_thread( NULL, MICO_APPLICATION_PRIORITY+1, "t3", run, 0x800, p_name3 ); require_noerr(err, exit); err = mico_rtos_create_thread( NULL, MICO_APPLICATION_PRIORITY+1, "t4", run, 0x800, p_name4 ); require_noerr(err, exit); exit: if( err != kNoErr ) os_mutex_log( "Thread exit with err: %d", err ); mico_rtos_delete_thread(NULL); return err; }
void mutex_thread(void *inContext) { int delay; char *thread_name = (char *)inContext; srand( 1000 ); while(1) { delay = rand()%9 + 1; mico_rtos_lock_mutex(&os_mutex); os_mutex_log("%s thread is using resources, delay %ds", thread_name, delay); mico_thread_sleep(delay); os_mutex_log("%s thread will release resource", thread_name); mico_rtos_unlock_mutex(&os_mutex); mico_thread_sleep(5); } }
int application_start( void ) { OSStatus err = kNoErr; err = mico_rtos_init_mutex(&os_mutex); require_noerr( err, exit ); err = mico_rtos_create_thread(NULL, MICO_APPLICATION_PRIORITY, "mutex1", mutex_thread, 0x800, (void *)os_mutex1); require_noerr_action( err, exit, os_mutex_log("ERROR: Unable to start the mutex1 thread.") ); err = mico_rtos_create_thread(NULL, MICO_APPLICATION_PRIORITY, "mutex2", mutex_thread, 0x800, (void *)os_mutex2); require_noerr_action( err, exit, os_mutex_log("ERROR: Unable to start the mutex2 thread.") ); err = mico_rtos_create_thread(NULL, MICO_APPLICATION_PRIORITY, "mutex2", mutex_thread, 0x800, (void *)os_mutex3); require_noerr_action( err, exit, os_mutex_log("ERROR: Unable to start the mutex2 thread.") ); return err; exit: os_mutex_log("ERROR, err: %d", err); return err; }
void run( void *arg ) { char *name = (char *)arg; char debug[20]; while(1) { MUTEX_LOCK(); if( g_tickets <= 0 ){ MUTEX_UNLOCK(); goto exit; } g_tickets--; sprintf( debug, "Thread %s, %d\r\n", name, g_tickets ); MicoUartSend(STDIO_UART, debug, strlen(debug) ); MUTEX_UNLOCK(); } exit: os_mutex_log( "thread: %s exit now", name ); mico_rtos_delete_thread(NULL); }