- 論壇徽章:
- 0
|
本帖最后由 o_unix 于 2012-10-09 22:22 編輯
大家好:我封裝一個(gè)類,用來(lái)管理db2上下文的。代碼如下:
- #include <iostream>
- using namespace std;
- #include <sqlca.h>
- #include <string.h>
- #include <pthread.h>
- #include <sql.h>
- // 用于保存上下文并標(biāo)識(shí)當(dāng)前上下文是否空閑, free 為 1時(shí)空閑,0 時(shí)在使用。
- struct ctxlist
- {
- void *ctx;
- int free;
- };
- class test
- {
- /*用于管理上下文訪問(wèn)*/
- pthread_mutex_t mutex;
- pthread_cond_t cond;
- struct ctxlist *list; //保存上下文的起始地址
- int use; // 沒(méi)有被使用的上下文
- int total; // 一共創(chuàng)建了多少個(gè)上下文
- public:
- test( int i, int ctxtype);
- ~test();
- int get(); //獲取一個(gè)空閑的上下文
- int unget( int i); // 釋放使用完的上下文
-
- };
- test::test( int i, int ctxtype)
- {
- total = i;
- pthread_mutex_init( &mutex, NULL);
- pthread_cond_init( &cond, NULL);
- list = new struct ctxlist[i];
- sqleSetTypeCtx( ctxtype);
- int l;
- struct sqlca sqlca;
- for( l = 0; l < total; l++)
- {
- sqleBeginCtx( &list[l].ctx, SQL_CTX_CREATE_ONLY, NULL, &sqlca);
- list[l].free = 1;
- }
- use = total;
- }
- test::~test()
- {
- int i;
- struct sqlca sqlca;
- for( i = 0; i < total; i++)
- {
- sqleEndCtx( &list[i].ctx, SQL_CTX_FREE_ONLY, NULL, &sqlca);
- }
- pthread_mutex_destroy( &mutex);
- pthread_cond_destroy( &cond);
- delete(list);
- }
- int test::get()
- {
- pthread_mutex_lock( &mutex);
- while( 0 == use)
- pthread_cond_wait( &cond, &mutex);
- int i;
- struct sqlca sqlca;
- for( i = 0; i < total; i++)
- {
- if( 1 == list[i].free)
- break;
- }
- list[i].free = 0;
- pthread_mutex_unlock( &mutex);
- return i;
- }
- int test::unget( int i)
- {
- pthread_mutex_lock( &mutex);
- list[i].free = 1;
- pthread_mutex_unlock( &mutex);
- pthread_cond_signal( &cond);
- return i;
- }
- void *pthread_func( void *arg);
- test tt(5, SQL_CTX_MULTI_MANUAL);
- int main( void )
- {
-
- pthread_t *tids = new pthread_t[10];
- int i;
- for( i = 0; i < 10; i++)
- pthread_create( tids+i, NULL, pthread_func, NULL);
- for( i = 0; i < 10; i++)
- {
- pthread_join( *(tids+i), NULL);
- }
- cout<<"main finishi"<<endl;
- return 0;
- }
- void *pthread_func( void *arg)
- {
- cout<<"pthread id: "<<pthread_self()<<endl;
- }
復(fù)制代碼 但是運(yùn)行的時(shí)候在 sqleEndCtx( &list.ctx, SQL_CTX_FREE_ONLY, NULL, &sqlca); 這句就發(fā)生錯(cuò)誤了。查看發(fā)現(xiàn)沒(méi)有無(wú)效的地址。請(qǐng)大家?guī)兔纯,我那里沒(méi)有考慮清楚?謝謝。 |
|