- 论坛徽章:
- 0
|
本帖最后由 o_unix 于 2012-10-09 22:22 编辑
大家好:我封装一个类,用来管理db2上下文的。代码如下:
- #include <iostream>
- using namespace std;
- #include <sqlca.h>
- #include <string.h>
- #include <pthread.h>
- #include <sql.h>
- // 用于保存上下文并标识当前上下文是否空闲, free 为 1时空闲,0 时在使用。
- struct ctxlist
- {
- void *ctx;
- int free;
- };
- class test
- {
- /*用于管理上下文访问*/
- pthread_mutex_t mutex;
- pthread_cond_t cond;
- struct ctxlist *list; //保存上下文的起始地址
- int use; // 没有被使用的上下文
- int total; // 一共创建了多少个上下文
- public:
- test( int i, int ctxtype);
- ~test();
- int get(); //获取一个空闲的上下文
- 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;
- }
复制代码 但是运行的时候在 sqleEndCtx( &list.ctx, SQL_CTX_FREE_ONLY, NULL, &sqlca); 这句就发生错误了。查看发现没有无效的地址。请大家帮忙看看,我那里没有考虑清楚?谢谢。 |
|