暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

ESQLC创建跨连接的线程安全的应用程序

Dr.王 2022-01-21
282

如果多线程应用程序需要使用同一个连接, 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)

 

当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表。

最后修改时间:2022-01-21 17:00:50
「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论