PDA

View Full Version : Multithreading problem



y.shan
13th December 2007, 13:13
Hi, my current situation is this:

I'm using threads in my application and i want to communicate with the main thread.
At the moment I'm doing it like this:

thread:


[...]
extern QMutex waitForUserLock;
extern QWaitCondition waitForUser;
[...]
text = [...];
customEvent * send_event = new customEvent(type);
send_event->setData((void*)text);

waitForUserLock.lock();
QApplication::postEvent((QObject*)mainwindow, send_event);
waitForUser.wait(&waitForUserLock); //sometimes hangs here
waitForUserLock.unlock();
[...]


mainwindow:


[...]
QMutex waitForUserLock;
QWaitCondition waitForUser;
[...]
void mainwindow::customEvent(QEvent *e)
{
customEvent *me = (customEvent *) e;
switch (me->type())
{
case type:
waitForUserLock.lock();
my_function((char*)me->data());
waitForUser.wakeOne();
waitForUserLock.unlock();
return;
[...]
}
}
[...]


The problem is the wait, where the application sometimes hangs.
Does anyone know where the mistake is or is there a better solution?

DeepDiver
13th December 2007, 13:18
you can use signals and slots for cross thread communication.
Meaning: you emit a signal in one thread and catch it in a slot in the main thread.

Good luck,

Tom

high_flyer
13th December 2007, 13:20
From the code you posted its hard to tell.
It sounds like you are having a dead lock (http://blogs.msdn.com/davidklinems/archive/2005/10/24/484275.aspx)
Two things:
1. Don't use gloabl mutexes, and remember, you should mutex data /resources , not code.
2. Try using tryLock().

y.shan
13th December 2007, 13:20
you can use signals and slots for cross thread communication.
Meaning: you emit a signal in one thread and catch it in a slot in the main thread.

Good luck,

Tom

yeah, but isn't this the same as using events?

high_flyer
13th December 2007, 13:21
yeah, but isn't this the same as using events?
Yes it is, its what Qt4 does in the background with the signals.