Solved

Multi Thread in C++ with CORBA

Posted on 2001-07-02
5
566 Views
Last Modified: 2008-02-01
I'm writing a multi thread C++/CORBA application.

Everytime when client calls server program passing
CORBA structure as an argument, CORBA creates a thread
for a server function for queries. Each funcion (thread)
allocates new CTX, makes DB connection of its own,
executes some queries, and copies the query result to
CORBA structre to pass it back to client.

It first seemed OK, but I found that sometimes the
program crashes making core dumped. It seems that after
one thread completes its job, it tries to free buff,
which was already allocated to other thread and freed
already... I'm not sure.

Please check the dbx result and my program source below.

Thanks in advance.

1. Follwings are the dbx result:
===========================================  
          ...........
detected a multithreaded program
dbx: program is not active
t@24 (l@6) terminated by signal SEGV (no mapping at the fault address)
Current function is MyAnySeq::_IDL_SEQUENCE_any::freebuf
  191               _data[ _index - 1 ].CORBA::Any::~any ();
(dbx)  dump
_ index = 1U
_data = 0x220dc8
          ...........

===========================================

2.C++ class looks like follow:

//--2.1 ThradFilter Member function for Creating threads--

int
ThreadFilter::inRequestPreMarshal(
                    CORBA::Request& rReq,
                    CORBA::Environment& )
{
    thread_t    Tid ;

    thr_create( NULL, 0, startThread, (void*) &rReq, THR_DETACHED, &Tid ) ;
    NB_LOG( NBcLog::EN_DEBUG,
        fprintf(stderr, "CORBA :: Thread Deleted : tid=%d\n",Tid) ) ;
    return -1 ;
}

static void*
startThread( void* pReq )
{
    CORBA::Orbix.continueThreadDispatch( *(CORBA::Request*) pReq ) ;
    NB_LOG( NBcLog::EN_DEBUG,
        fprintf(stderr, "xMXIO :: Thread Created : tid=%d\n",thr_self()) ) ;
    return NULL ;
}

          ...........



//--2.2 My Class for query----------
MyClass::MyClass( void )
{   //executed once when MyClass is instanced
    EXEC SQL ENABLE THREADS;

}

          ...........

      //******************************************
      //following function is called in every thread
      //******************************************
int
MyClass::CalledByClient(
    NBosOMD::stMoDisLoginInfoReq    in_stDisLoginInfoReq,  
    MyAnySeq::BIOSMsg*&             out_rBiosMsg)          
{

EXEC ORACLE OPTION (ORACA=YES);
EXEC ORACLE OPTION (RELEASE_CURSOR=YES);

    NBosOMD::stR_Login_Info         st_LoginInfo;

EXEC SQL BEGIN DECLARE SECTION;
   ........

    struct  stR_Login_Info
    {
        ..........
    } get_LoginInfo;

    struct  stR_Login_Info_Ind        
    {                                  
      ............      
 } LoginInfo_Ind;

    int             SQL_boat = NO_ERROR;
    VARCHAR         pUserID[50];    
    VARCHAR         pPasswd[50];  
    struct sqlca    sqlca;
    sql_context     ctx;

EXEC SQL END  DECLARE SECTION;

    MyClass::Cleaner();

    EXEC SQL WHENEVER SQLERROR DO LogOracleError(sqlca, &SQL_boat,"CalledByClient");

    EXEC SQL CONTEXT ALLOCATE :ctx;

    memset(&pUserID, 0x00, sizeof(pUserID));
    memset(&pPasswd, 0x00, sizeof(pPasswd));
    pUserID.len = sprintf((char *)pUserID.arr,"%s", ID);
    pPasswd.len = sprintf((char *)pPasswd.arr,"%s", PASSWD);

    EXEC SQL CONNECT :pUserID IDENTIFIED BY :pPasswd;

    oraca.orastxtf = ORASTFERR;

    qGuiId = in_stDisLoginInfoReq.mGuiId;
    memset(qUserName, 0x00, sizeof(qUserName));
    strncpy(qUserName, in_stDisLoginInfoReq.mpUserName, 12-1);

    EXEC SQL DECLARE loginInfo_Cursor CURSOR FOR
        SELECT  ... FROM ..

    EXEC SQL OPEN loginInfo_Cursor ;

    EXEC SQL WHENEVER NOT FOUND DO break;

    int AnyCnt=0;
    out_rBiosMsg->msgBody.length(MAX_ANY_CNT);      // MAX_ANY_CNT = 500
    while(1)
   {
        memset(&st_LoginInfo, 0, sizeof(st_LoginInfo));
        memset(&get_LoginInfo,0, sizeof(get_LoginInfo));
        memset(&LoginInfo_Ind,0, sizeof(LoginInfo_Ind));

        EXEC SQL FETCH loginInfo_Cursor
                  INTO :get_LoginInfo INDICATOR :LoginInfo_Ind;

        if (sqlca.sqlcode != 0)
        {
            if (sqlca.sqlcode != 1403)
            {
                printf(" ORACLE ERROR: %d\n", sqlca.sqlcode);
                fflush(stdout);
            }

            break;
        }

        //
        // copy the query result to CORBA AnySequence
        //
        st_LoginInfo.mGuiId     = get_LoginInfo.mGuiId;
        st_LoginInfo.mUserGrade = get_LoginInfo.mUserGrade;

        strncpy(st_LoginInfo.mpUserName ,(char *)get_LoginInfo.mpUserName.arr,
                 get_LoginInfo.mpUserName.len);

        out_rBiosMsg->msgBody[AnyCnt++] <<= st_LoginInfo;  

    }


    EXEC SQL WHENEVER NOT FOUND continue;

    EXEC SQL CLOSE loginInfo_Cursor;
    EXEC SQL COMMIT WORK RELEASE;
    EXEC SQL CONTEXT FREE :ctx;

    out_rBiosMsg->msgBody.length(AnyCnt);        // Assign Any Data count

    return MyClass::LogFuncResult(
        "Call_GetLoginInfo_CursorProc()", "R_LOGIN_INFO",SQL_boat);
}


int
MyClass::LogFuncResult(
    char*   functionName,
    char*   tableName,
    int     SQL_boat)
{

    NB_LOG( NBcLog::EN_DEBUG,
        NBcLog::writeLog( NBcLog::EN_INF, 0,
        "[%s]%s:%s -> SQL_boat = %d\n",
            tableName,
            functionName,
            (SQL_boat == NO_ERROR) ? "Success" : "Fail",
            SQL_boat));

    //
    // SQL_boat?? NO_ERROR ?? ??????  ????.
    //
    return  (SQL_boat == NO_ERROR) ? NBcRlt::EN_TRUE : NBcRlt::EN_FALSE;
    //return SQL_ErrCode;
}


void
NBcRD_DBAccess_Impl::LogOracleError(
    struct sqlca    sqlca,
    int*            SQL_boat,
    char*           FuncName
    )
{

    EXEC SQL WHENEVER SQLERROR CONTINUE;

    NB_LOG( NBcLog::EN_BASIC,
        NBcLog::writeLog( NBcLog::EN_ERR, NBcErr::EN_DB_TRANSACTION_ERR,
        "\n[%s] ORACLE ERR:%d: % .70s \n\n", FuncName, sqlca.sqlcode,
        sqlca.sqlerrm.sqlerrmc)) ;

    *SQL_boat = ERROR_OCC;

}

===========================================

3. Idl File:

module MyAnySeq
{

     .............
    typedef sequence<any>   AnySeq ;
    struct  BIOSMsg
    {
        char    neType ;        
        char    msgType ;    
        short   opCode ;      
        long    seqNo ;        
        short   linkedReply ;
        short   result ;        
        char    rowCnt ;    
        char    tid ;          
        char    ssid ;        
        char    oid ;          
        char    sid ;          
        char    cid ;          
        char    lid ;          
        char    rsv1 ;        
        long    length ;      
        AnySeq  msgBody ;       // Message Body
    } ;

    .......................
}
0
Comment
Question by:doolydooly
  • 3
  • 2
5 Comments
 
LVL 14

Expert Comment

by:AlexVirochovsky
ID: 6248423
may be next helps you:
....
I use similar approach in my project. I have multithread process, and one of
threads is responsible to do orb->run (only that, nothing more).
Data received by server are than put in internal queue and processed by
other threads.
We use TAO ORB and it works fine. poa->activate is done in main thread
(thread of main function). Until now we didn't find any problem with this
approach.

Kresimir Blauhorn
....
see  
http://www.cs.wustl.edu/~schmidt/C++-report-col15.ps.gz 
http://www.cs.wustl.edu/~schmidt/C++-report-col16.ps.gz 

for more information on this.


0
 
LVL 14

Accepted Solution

by:
AlexVirochovsky earned 50 total points
ID: 6261983
I don't know, is my comment help you, but if not,
you can simple reject my reply.Alex
0
 

Author Comment

by:doolydooly
ID: 6264100
Thanks for the answer.

I initialized CTX variables allocated
to each thread (with memset), and it worked!
Thanks for your help.

=====================================================
ThreadedFunction(..)
{  
EXEC BEGIN DECLARE SECTION
sql_context ctx;
struct sqlca sqlca;
.........
EXEC END DECLARE SECTION

              .......

    // following two lines are added and it worked
    memset(&ctx, 0x00, sizeof(ctx));
    memset(&sqlca, 0x00, sizeof(sqlca));

    EXEC SQL CONTEXT ALLOCATE :ctx;
    EXEC SQL CONTEXT USE :ctx;
     
         .........
}
0
 
LVL 14

Expert Comment

by:AlexVirochovsky
ID: 6265509
Ok, fine! Now you may evaluate my reply.
0
 

Author Comment

by:doolydooly
ID: 6267294
Isn't it evaulated? I DID evaulate your answer, but maybe there was some error. I'm trying it again.  Let me know if it didn't work.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
How to programmatically differentiate between C and Java 10 188
Grammars for C C++ and java 1 114
Best book to learn C++ 4 70
Path to  STL Map header file 1 43
In days of old, returning something by value from a function in C++ was necessarily avoided because it would, invariably, involve one or even two copies of the object being created and potentially costly calls to a copy-constructor and destructor. A…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.

920 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now