MySQL:跨多个线程的事务 [英] MySQL: Transactions across multiple threads

查看:394
本文介绍了MySQL:跨多个线程的事务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

初步:

我有一个应用程序,该应用程序维护约100个线程的线程池.每个线程可以持续大约1-30秒,然后再替换新任务.当一个线程结束时,该线程几乎总是会导致在表中插入1-3条记录,所有线程都使用该表.目前,尚无交易支持,但我现在尝试添加.此外,有问题的表是InnoDB.所以...

I have an application which maintains a thread pool of about 100 threads. Each thread can last about 1-30 seconds before a new task replaces it. When a thread ends, that thread will almost always will result in inserting 1-3 records into a table, this table is used by all of the threads. Right now, no transactional support exists, but I am trying to add that now. Also, the table in question is InnoDB. So...

目标

我想为此进行交易.此事务是否提交或回滚的规则驻留在主线程中.基本上,有一个简单的函数可以返回布尔值.

I want to implement a transaction for this. The rules for whether or not this transaction commits or rollback reside in the main thread. Basically there is a simple function that will return a boolean.

  1. 我可以跨多个连接实现事务吗?
  2. 如果没有,多个线程可以共享同一连接吗? (注意:这里有很多插入物,这是必需的.)

推荐答案

好吧,正如另一个答案所述,您不能跨多个连接创建事务.您可以跨线程共享单个连接. 但是您需要对此非常小心.您需要确保同时只有一个线程正在写入连接.您不能只让多个线程在同一个连接上交谈,而无需以某种方式同步它们的活动.如果您允许两个线程同时通话,则可能会发生不好的事情(客户端库中的内存损坏等).使用互斥或​​关键部分来保护连接对话可能是解决方法.

Well, as stated in a different answer you can't create a transaction across multiple connections. And you can share the single connection across threads. However you need to be very careful with that. You need to make sure that only one thread is writing to the connection at the same time. You can't just have multiple threads talking across the same connection without synchronizing their activities in some way. Bad things will likely happen if you allow two threads to talk at once (memory corruptions in the client library, etc). Using a mutex or critical section to protect the connection conversations is probably the way to go.

-唐

这篇关于MySQL:跨多个线程的事务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆