zoukankan      html  css  js  c++  java
  • MySql多线程访问

    如果你用线程的编程,你应该用--with-thread-safe-client编译MySQL C API,这将使C API线程对每个连接更安全。你可以让2个线程共享相同的连接,只要如果你做下列事情:

    两个线程不能同时在同一个连接上发送查询到MySQL。特别是你必须保证在一个mysql_query()和mysql_store_result()之间没有其他线程正在使用同一个连接。

    许多线程能存取用mysql_store_result()检索出来的不同结果集合。

    如果你使用mysql_use_result,你必须保证没有其他线程在同一个连接上正在询问任何东西,直到结果集合被关闭。

    设计如下线程,验证上述内容, Thread1和Thread2使用同一个mysql连接,执行select语句:

    Thread1:                                               Thread2:

         mysql_query();                                    sleep(1);

                  |                                                       |

                  |                                                       |

             sleep(2);                                      mysql_query();

                  |                                                       |

                  |                                                       |

      mysql_store_result();                      mysql_store_result();

    线程2中调用mysql_query()时出错,通过mysql_error()返回的错误信息为:Commands out of sync; you can’t run this command now.

    解决方法1:

    一个线程分配一个mysql连接

    解决方法2:

    在mysql_query()之前加上线程锁,在mysql_store_result()之后释放线程锁,

    pthread_mutex_lock();

    |

    |

    mysql_query();

    |

    |

    mysql_store_result();

    |

    |

    pthread_mutex_unlock();

    附(来自于MySql 文档):

    Two threads can't send a query to the MySQL server at the same time on the same connection.
    In particular, you have to ensure that between a mysql_query() and mysql_store_result() no other thread is using the same connection.
  • 相关阅读:
    PAT 甲级 1115 Counting Nodes in a BST (30 分)
    PAT 甲级 1114 Family Property (25 分)
    PAT 甲级 1114 Family Property (25 分)
    Python Ethical Hacking
    Python Ethical Hacking
    Python Ethical Hacking
    Python Ethical Hacking
    Python Ethical Hacking
    Python Ethical Hacking
    Python Ethical Hacking
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13318581.html
Copyright © 2011-2022 走看看