How can I sync Qthreads ?
-
Hello,
I'm working with Qthreads in my program, but I'm having a problem with the syncronization. I'm acessing an Api to save the data in the database, but it's not working beacuse the Threads are not sync.
So I'll like to know hoe can I sync the Qthreads to make sure not more than one tread it's accesing the api at the same time.
I try ussing Qmutex and Qwaitcodition but it didn't work.
Thanks
-
I use QMutex to lock and unlock everytime I need to send a request to the Api. Like this:
void Task::log(){ sync.lock(); currentapi->createLog(currentapi->jsonUser["id"].toInt(),currentapi->jsonSession["id"].toInt(),QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz")); sync.unlock(); } void Task::clog(){ sync.lock(); currentapi->closeLog(currentapi->jsonUser["id"].toInt(),currentapi->jsonLog["id"].toInt(),capThread->url, capThread->url,QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz")); sync.unlock(); } void Task::activity(){ sync.lock(); currentapi->newActivity(currentapi->jsonUser["id"].toInt(), idlog,"Qt Creator", Mcount, Kcount, "task.cpp - PerfQ_Client - Qt Creator",QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz")); sync.unlock(); }
The three methods are slots, and the signals to this slots come from diferents threads.
sync is the Qmutex.But it doesn't work, the program starts fine but when clog it's call the program stops working.
-
Hi,
Did you check that you are returning from log at some point ? Are you maybe blocked in createLog ?
-
@SujaMM said:
The three methods are slots, and the signals to this slots come from diferents threads.
If
Task
is executed in a separate thread and is the only one accessing to the log you don't need to protect with mutex because by defaultconnect
usesQueuedConnection
to call slots across threads.BTW, if you want/need mutexes I suggest also to use
QMutexLocker
; it is useful to avoid deadlocks if one function called between lock/ulock raises exceptions -
Task is the main thread, I have two other threads that will emit the signal, one to call the slot log and the other one to call clog. while the signal to call the slot activity it's in the main thread.
The think it's that the log it's call every minute and the clog it's call also every minute, but a minute after log it's call. The problem it's that the activity it's call every 20 seconds, and if log o clog are call at the same time as the activity the api can't handle both request and one of the request it's end returning a null pointer.
I don't know if this explain the problem better. I'll try with the QMutexLocker.
Thanks