本文介绍了如何在c ++中超时mysql ++查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用mysql ++为了连接到MySQL数据库执行一堆数据查询。由于我正在读取的表不断被写入,并且我需要一个一致的数据视图,我首先锁定表。但是,MySQL在其锁查询中没有NOWAIT的概念,因此如果这些表被其他东西锁定,使它们被锁定很长时间,我的应用程序就在那里等待。我想要的是能够返回并说锁定无法获得,并在几秒钟后再试。我在这个超时的一般尝试如下。

I am using mysql++ in order to connect to a MySQL database to perform a bunch of data queries. Due to the fact that the tables I am reading from are constantly being written to, and that I need a consistent view of the data, I lock the tables first. However, MySQL has no concept of 'NOWAIT' in its lock query, thus if the tables are locked by something else that keeps them locked for a long time, my application sits there waiting. What I want it to do is to be able to return and say something like 'Lock could no be obtained' and try again in a few seconds. My general attempt at this timeout is below.

如果我在数据库锁定表后运行这个,我得到的消息,超时被击中, t知道如何获取mysql_query行终止。我会感谢任何帮助/想法!

If I run this after locking the table on the database, I get the message that the timeout is hit, but I don't know how to then get the mysql_query line to terminate. I'd appreciate any help/ideas!


volatile sig_atomic_t success = 1;

void catch_alarm(int sig) {
        cout << "Timeout reached" << endl;
        success = 0;
        signal(sig,catch_alarm);
}

// connect to db etc.
// *SNIP

signal (SIGALRM, catch_alarm);
alarm(2);
mysql_query(p_connection,"LOCK TABLES XYZ as write");


推荐答案

方式:

您在单独的线程上执行查询,无论是否发生超时都会继续运行。超时发生在主线程,并将变量设置为1,标记它发生。然后你做你想做的任何你的主线程。

You execute the query on a separate thread, that keeps running whether or not the timeout occurs. The timeout occurs on the main thread, and sets a variable to "1" marking that it occurred. Then you do whatever you want to do on your main thread.

查询线程在查询完成后会检查是否发生超时。如果没有,它做它需要做的其余工作。如果它已经存在,它只是解锁它刚刚锁定的表。

The query thread, once the query completes, checks if the timeout has occurred. If it hasn't, it does the rest of the work it needs to do. If it HAS, it just unlocks the tables it just locked.

我知道这听起来有点浪费,但锁定解锁时间应该基本上是瞬间的,你尽可能接近你想要的结果。

I know it sounds a bit wasteful, but the lock-unlock period should be basically instantaneous, and you get as close to the result you want as possible.

这篇关于如何在c ++中超时mysql ++查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-28 04:10
查看更多