⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 mutex3.c

📁 ecos实时嵌入式操作系统
💻 C
📖 第 1 页 / 共 2 页
字号:
//==========================================================================////        mutex3.cxx////        Mutex test 3 - priority inheritance////==========================================================================//####ECOSGPLCOPYRIGHTBEGIN####// -------------------------------------------// This file is part of eCos, the Embedded Configurable Operating System.// Copyright (C) 1998, 1999, 2000, 2001, 2002 Red Hat, Inc.//// eCos is free software; you can redistribute it and/or modify it under// the terms of the GNU General Public License as published by the Free// Software Foundation; either version 2 or (at your option) any later version.//// eCos is distributed in the hope that it will be useful, but WITHOUT ANY// WARRANTY; without even the implied warranty of MERCHANTABILITY or// FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License// for more details.//// You should have received a copy of the GNU General Public License along// with eCos; if not, write to the Free Software Foundation, Inc.,// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.//// As a special exception, if other files instantiate templates or use macros// or inline functions from this file, or you compile this file and link it// with other works to produce a work based on this file, this file does not// by itself cause the resulting work to be covered by the GNU General Public// License. However the source code for this file must still be made available// in accordance with section (3) of the GNU General Public License.//// This exception does not invalidate any other reasons why a work based on// this file might be covered by the GNU General Public License.//// Alternative licenses for eCos may be arranged by contacting Red Hat, Inc.// at http://sources.redhat.com/ecos/ecos-license/// -------------------------------------------//####ECOSGPLCOPYRIGHTEND####//==========================================================================//#####DESCRIPTIONBEGIN####//// Author(s):     hmt// Contributors:  hmt, nickg, jlarmour// Date:          2000-01-06// Description:   Tests mutex priority inheritance. This is simply a translation//                of the similarly named kernel test to the POSIX API//####DESCRIPTIONEND####// ------------------------------------------------------------------------#include <cyg/infra/testcase.h>#include <pkgconf/posix.h>#include <pkgconf/system.h>#ifdef CYGPKG_KERNEL#include <pkgconf/kernel.h>#endif#ifdef CYGPKG_ISOINFRA# include <sys/types.h># include <pthread.h># include <semaphore.h># include <time.h># include <unistd.h>#endif#if !defined(CYGPKG_POSIX_PTHREAD)#define NA_MSG "POSIX threads not enabled"// ------------------------------------------------------------------------//// These checks should be enough; any other scheduler which has priorities// should manifest as having no priority inheritance, but otherwise fine,// so the test should work correctly.#elif !defined(_POSIX_THREAD_PRIORITY_SCHEDULING)#define NA_MSG "No POSIX thread priority scheduling enabled"#elif !defined(_POSIX_THREAD_PRIO_INHERIT)#define NA_MSG "No POSIX thread priority inheritance enabled"#elif !defined(_POSIX_SEMAPHORES)#define NA_MSG "No POSIX sempaphore support enabled enabled"#elif !defined(CYGFUN_KERNEL_API_C)#define NA_MSG "Kernel C API not enabled"#elif defined(CYGPKG_KERNEL_SMP_SUPPORT)#define NA_MSG "Test cannot run with SMP support"#endif#ifdef NA_MSGvoidcyg_start(void){    CYG_TEST_INIT();    CYG_TEST_NA(NA_MSG);}#else#include <cyg/infra/cyg_ass.h>#include <cyg/infra/cyg_trac.h>#include <cyg/infra/diag.h>             // diag_printf#include <cyg/kernel/kapi.h>            // Some extras// ------------------------------------------------------------------------// Management functions//// Stolen from testaux.hxx and copied in here because I want to be able to// reset the world also.// ... and subsequently POSIXized out of all similarly with its progenitors.#define NTHREADS 7#define STACKSIZE (PTHREAD_STACK_MIN*2)static pthread_t thread[NTHREADS] = { 0 };typedef CYG_WORD64 CYG_ALIGNMENT_TYPE;static CYG_ALIGNMENT_TYPE stack[NTHREADS] [   (STACKSIZE+sizeof(CYG_ALIGNMENT_TYPE)-1)     / sizeof(CYG_ALIGNMENT_TYPE)                     ];// Semaphores to halt execution of threads     static sem_t hold[NTHREADS];// Flag to tell all threads to exitstatic int all_exit;// Application thread data is passed here, the thread// argument is static CYG_ADDRWORD thread_data[NTHREADS];static volatile int nthreads = 0;// Sleep for 1 tick...static struct timespec sleeptime;static pthread_t new_thread( void *(*entry)(void *),                             CYG_ADDRWORD data,                             int priority,                             int do_resume){    pthread_attr_t attr;    int _nthreads = nthreads++;    struct sched_param schedparam;    schedparam.sched_priority = priority;            pthread_attr_init( &attr );    pthread_attr_setstackaddr( &attr, (void *)((char *)(&stack[_nthreads])+STACKSIZE) );            pthread_attr_setstacksize( &attr, STACKSIZE );    pthread_attr_setinheritsched( &attr, PTHREAD_EXPLICIT_SCHED );    pthread_attr_setschedpolicy( &attr, SCHED_RR );    pthread_attr_setschedparam( &attr, &schedparam );        CYG_ASSERT(_nthreads < NTHREADS,                "Attempt to create more than NTHREADS threads");    thread_data[_nthreads] = data;    sem_init( &hold[_nthreads], 0, do_resume ? 1 : 0 );    all_exit = 0;    pthread_create( &thread[_nthreads],                    &attr,                    entry,                    (void *)_nthreads);    return thread[_nthreads];}static void kill_threads( void ){    CYG_ASSERT(nthreads <= NTHREADS,                "More than NTHREADS threads");    CYG_ASSERT( pthread_equal(pthread_self(),thread[0]),                "kill_threads() not called from thread 0");    all_exit = 1;    while ( nthreads > 1 ) {        nthreads--;        if ( 0 != thread[nthreads] ) {            sem_post( &hold[nthreads] );            pthread_cancel( thread[nthreads] );            pthread_join( thread[nthreads], NULL );            thread[nthreads] = 0;            sem_destroy( &hold[nthreads] );        }    }    CYG_ASSERT(nthreads == 1,               "No threads left");}// ------------------------------------------------------------------------#define DELAYFACTOR 1 // for debugging// ------------------------------------------------------------------------pthread_mutex_t mutex;// These are for reporting back to the master threadvolatile int got_it  = 0;volatile int t3ran   = 0;volatile int t3ended = 0;volatile int extras[4] = {0,0,0,0};    volatile int go_flag = 0; // but this one controls thread 3 from thread 2// ------------------------------------------------------------------------// 0 to 3 of these run generally to interfere with the other processing,// to cause multiple prio inheritances, and clashes in any orders.static void *extra_thread( void *arg ){#define XINFO( z ) \    do { z[13] = '0' + data; CYG_TEST_INFO( z ); } while ( 0 )    static char running[]  = "Extra thread Xa running";    static char exiting[]  = "Extra thread Xa exiting";    static char resumed[]  = "Extra thread Xa resumed";    static char locked[]   = "Extra thread Xa locked";    static char unlocked[] = "Extra thread Xa unlocked";    int id = (int)arg;    CYG_ADDRWORD data = thread_data[id];    CYG_ASSERT( (id >= 4 && id <= 6), "extra_thread invalid id" );        // Emulate resume behaviour    sem_wait( &hold[id] );    if( all_exit ) return 0;        XINFO( running );    sem_wait( &hold[id] );        XINFO( resumed );    pthread_mutex_lock( &mutex );    XINFO( locked );    pthread_mutex_unlock( &mutex );        XINFO( unlocked );    extras[ data ] ++;    XINFO( exiting );    return NULL;}// ------------------------------------------------------------------------static void *t1( void *arg ){    int id = (int)arg;    //CYG_ADDRWORD data = thread_data[id];        // Emulate resume behaviour    sem_wait( &hold[id] );    if( all_exit ) return 0;    CYG_TEST_INFO( "Thread 1 running" );    sem_wait( &hold[id] );        pthread_mutex_lock( &mutex );    got_it++;    CYG_TEST_CHECK( 0 == t3ended, "T3 ended prematurely [T1,1]" );    pthread_mutex_unlock( &mutex );    CYG_TEST_CHECK( 0 == t3ended, "T3 ended prematurely [T1,2]" );    // That's all.    CYG_TEST_INFO( "Thread 1 exit" );    return 0;    }// ------------------------------------------------------------------------static void *t2( void *arg ){    int i;    int id = (int)arg;    CYG_ADDRWORD data = thread_data[id];    cyg_tick_count_t now, then;        // Emulate resume behaviour    sem_wait( &hold[id] );    if( all_exit ) return 0;    CYG_TEST_INFO( "Thread 2 running" );    CYG_TEST_CHECK( 0 == (data & ~0x77), "Bad T2 arg: extra bits" );    CYG_TEST_CHECK( 0 == (data & (data >> 4)), "Bad T2 arg: overlap" );    sem_wait( &hold[id] );    // depending on our config argument, optionally restart some of the    // extra threads to throw noise into the scheduler:    for ( i = 0; i < 3; i++ )        if ( (1 << i) & data )          // bits 0-2 control            sem_post( &hold[i+4] );     // made sure extras are thread[4-6]    // let those threads run    for( i = 0; i < DELAYFACTOR * 10; i++ )        nanosleep( &sleeptime, NULL );    cyg_scheduler_lock();               // do this next lot atomically    go_flag = 1;                        // unleash thread 3    sem_post( &hold[1] );               // resume thread 1    // depending on our config argument, optionally restart some of the    // extra threads to throw noise into the scheduler at this later point:    for ( i = 4; i < 7; i++ )        if ( (1 << i) & data )          // bits 4-6 control            sem_post( &hold[i] );       // made sure extras are thread[4-6]    cyg_scheduler_unlock();             // let scheduling proceed    // Need a delay (but not a CPU yield) to allow t3 to awaken and act on    // the go_flag, otherwise we check these details below too soon.    // Actually, waiting for the clock to tick a couple of times would be    // better, so that is what we will do.  Must be a busy-wait.    then = cyg_current_time();    do {        now = cyg_current_time();        // Wait longer than the delay in t3 waiting on go_flag

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -