PDA

View Full Version : QMutex



weixj2003ld
14th April 2009, 08:31
When I create two threads,and synchronize them with QMutex,Do I define a mutex(QMutex) as a local varable(that is,mutex is defined respectively in two threads) or a global one(that is ,the two threads visit the same mutex)?

Grimlock
14th April 2009, 08:43
The two threads need to work on the same QMutex object.

weixj2003ld
14th April 2009, 09:17
but in the mandelbrot (an example of qt4.3.1) ,the mutex is defined in the child thread,why?

Grimlock
14th April 2009, 09:33
That got me thinking. But if You look at the MandelbrotWidget class only one worker thread is used. AFAIK to protect your data with a mutex all thread accessing the data need to operate on the same mutex object, be it via global definition, pointer or reference.

weixj2003ld
14th April 2009, 10:02
Thank u for ur answer.
your means is that:If the sharing data(visited by all threads) is global defination , a pointer or reference,I must define a mutex and it must be a global one?

Grimlock
14th April 2009, 10:20
If the sharing data(visited by all threads) If the data can be accessed by all the threads (regardless of the way the data is stored) You need to protect it with a mutex.

be it via global definition, pointer or reference
This part was just a hint that You can define your thread class to store the mutex via a pointer.

Class MyThread : public QThread
{
public:
MyThread(QMutex* mutex);
/* run etc.. */
private:
QMutex* myMutex;
};

wysota
14th April 2009, 22:32
@weixj2003ld: I really suggest you get some book on multithreading. Silberschatz's book on operating systems is a classic so you might want to have a look at it. You're asking basic questions on mutexes over and over again and it seems you are not learning from the answers you are getting because you come back and ask almost the same question again. If you are working on a school assignment, which it seems you are, we can help you in a limited scope only - we have a rule of not solving school assignments for people. So unless you prove me wrong, I'll be closely monitoring your threads and deleting all replies that look like complete solutions to your multithreading questions. We want to help you but we will not solve your school tasks for you or else you will learn nothing from them. Bear in mind you are repeatedly asking questions that are practically out of the scope of this forum. Now please open your favourite search engine and type in "mutex" or "thread synchronization".