更新日期:2024年09月11日
在多线程环境下使用GBase C API
#include
#include
#include
#include "gbase.h"
GBase 8a 程序员手册C API 篇
- 82 -
南大通用数据技术股份有限公司
#include
static pthread_mutex_t lock_thread_num;
static pthread_cond_t cond_thread_num;
static int thread_num;
void* th_new(void* arg)
{
GBASE* gbase;
GBASE_RES *res;
gbase_thread_init();
gbase = gbase_init(0);
if(!gbase_real_connect(gbase,"192.168.111.96","root","1111",
"test",5258, NULL, 0))
{
fprintf(stderr, "%s\n", gbase_error(gbase));
goto exit;
}
exit:
gbase_close(gbase);
gbase_thread_end();
pthread_mutex_lock(&lock_thread_num);
thread_num--;
pthread_cond_signal(&cond_thread_num);
pthread_mutex_unlock(&lock_thread_num);
pthread_exit(0);
return 0;
}
int main()
{
pthread_t t;
unsigned int i=10;
int error;
GBase 8a 程序员手册C API 篇
南大通用数据技术股份有限公司
- 83 -
pthread_attr_t thr_attr;
if(gbase_library_init(0, NULL, NULL))
{
exit(1);
}
thread_num = i;
if ((error=pthread_cond_init(&cond_thread_num,NULL)))
{
exit(1);
}
pthread_mutex_init(&lock_thread_num, NULL);
if ((error=pthread_attr_init(&thr_attr)))
{
exit(1);
}
if
((error=pthread_attr_setdetachstate(&thr_attr,PTHREAD_CREATE_DETACHE
D)))
{
exit(1);
}
while(i--)
{
pthread_create(&t, &thr_attr, th_new, NULL);
}
pthread_mutex_lock(&lock_thread_num);
while(thread_num > 0)
{
if
((error=pthread_cond_wait(&cond_thread_num,&lock_thread_num)))
fprintf(stderr,"\nGot error: %d from
pthread_cond_wait\n",error);
}
pthread_mutex_unlock(&lock_thread_num);
GBase 8a 程序员手册C API 篇
- 84 -
南大通用数据技术股份有限公司
pthread_mutex_destroy(&lock_thread_num);
gbase_library_end();
return 0;
}