安全|GBase8s ESQL/C 跨线程连接

如果多线程应用程序需要使用同一个连接, GBase8s ESQL/C应用程序必须管理连接。
最简单的方式是将SET CONNECTION语句放到一个循环中。
/* wait for connection: error -1802 indicates that the connection is in use */
do
{
EXEC SQL SET CONNECTION :con_name;
} while (SQLCODE == -1802)
【安全|GBase8s ESQL/C 跨线程连接】
当SQLCODE不等于-1802,说明在当前线程中,SET CONNECTION已经正确设定当前连接。

下面的代码片段显示跨连接的多线程应用程序
main()
{
EXEC SQL BEGIN DECLARE SECTION;
Int a;
EXEC SQL END DECLARE SECTION;
start_thread(); /* start 2 threads */

EXEC SQL SET CONNECTION ‘con1’;
EXEC SQL update table t1 set a = 40 where a = 10;

/* disconnect all connections */
EXEC SQL DISCONNECT ALL;
}
thread_1()
{
EXEC SQL connect to ‘db1’ as ‘con1’;
EXEC SQL insert into table t1 values(10); /* table t1 is in db1 */

/* make con1 available to other thread */
EXEC SQL set connection ‘con1’ dormant;

/* wait for con2 to become available and then update t2 */
do
{
EXEC SQL SET CONNECTION ‘con2’;
} while (SQLCODE == -1802)
If (SQLCODE != 0)
{
return;
}
EXEC SQL update t2 set a = 12 where a= 10; /* table t2 is in db2 */
EXEC SQL set connection ‘con2’ dormant;
}
thread_2()
{
/* make con2 an active connection */
EXEC SQL connect to ‘db2’ as ‘con2’;
EXEC SQL insert into table t2 values(10); /* t able t2 is in db2 */
/* make con2 available to other thread */
EXEC SQL set connection ‘con2’ dormant;
}

在上面的代码片段中, thread_1()使用SET CONNECTION循环等待con2变得可以使用。
当thread_2()设定为con2为dormant时,其他线程才能够使用con2, 在这个时候thread_1()中的SET CONNECTION才能够正确执行,然后更新t2表。

    推荐阅读