简体   繁体   English

如何在Qt / c ++中使用多线程通过Api访问我的数据库?

[英]How can I use multi thread in Qt/c++ to access my data base with an Api?

I have a problem, I'm connecting my program to the data base with an Api, to do this I use the network and webkit webkitwidgets funtions in Qt. 我有一个问题,我正在使用Api将程序连接到数据库,为此,我使用Qt中的网络和webkit webkitwidgets功能。 I have been able to do this without any problem. 我已经能够做到这一点,没有任何问题。

The think it's that I have to call some funtions in the api class from different threads. 认为这是我必须从不同的线程调用api类中的一些函数。

Firts I try passing the api object to the Qthread class, but I'm getting this error: 首先,我尝试将api对象传递给Qthread类,但出现此错误:

@QObject: Cannot create children for a parent that is in a different thread.
(Parent is SerialPort(0x24a1738), parent's thread is QThread(0x24a1770), current thread is QThread(0x18a8b0)

So I try ussing signals ans slots, it work with the firts function I use, a funtion to create what a call in my data base a log, but when I try to close the log, so I can send the information needed. 因此,我尝试使用信号ans插槽,它与我使用的firts函数一起使用,该功能可在数据库中创建对日志的调用,但是当我尝试关闭日志时,可以发送所需的信息。 I get this error: 我收到此错误:

 QEventLoop::exec: instance xxxxxx has already called exec()

What is the best way to work with Threads to avoid this problems ?? 避免这种问题的最佳方法是什么?

You haven't provided any code, only error messages. 您没有提供任何代码,仅提供了错误消息。 Since I have to guess, I'll say that you're creating a QObject -derived worker object and using the QObject::moveToThread method to change its thread affinity. 既然我不得不猜测,我会说您正在创建一个QObject派生的工作程序对象,并使用QObject::moveToThread方法更改其线程亲和力。 The problem in this case is that you've already given the worker object a parent. 在这种情况下,问题在于您已经为worker对象赋予了父对象。 You can't use moveToThread on an object that already has a parent. 您不能在已具有父对象的对象上使用moveToThread So, don't set the parent of your worker object when you create it and you should be good-to-go. 因此,创建对象时不要设置其工作对象的父对象,这应该是一个很好的选择。

As others users have commented, you will need to use signals & slots to initiate queries, etc. in your worker object. 正如其他用户所评论的那样,您将需要使用信号和插槽来发起工作对象中的查询等。 Qt will handle synchronization issues via the thread's event loop, so you don't have to worry about mutex locking, etc (as long as you use only sig/slot to invoke methods and get output values from the worker object). Qt将通过线程的事件循环处理同步问题,因此您不必担心互斥锁等(只要您仅使用sig / slot来调用方法并从worker对象获取输出值)。

Don't forget to call QThread::start to get the thread's event loop started. 不要忘记调用QThread::startQThread::start线程的事件循环。

NOTE 1: I assume you're using a fairly recent version of Qt (>= 4.8). 注意1:我假设您使用的是Qt的较新版本(> = 4.8)。

NOTE 2: If you're using QSqlDatabase and friends to access your DB, make sure to create the DB connection in the worker object after it is moved to the new thread. 注意2:如果您正在使用QSqlDatabase和朋友访问您的数据库,请确保将它移到新线程在worker对象中创建数据库连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM