Question

Consider the following code snippets:

class ThreadA::QThread
{
  public:
  ThreadA()
  {
  }
  void run()
  {
    myVariable = new int();
    *myVariable = 10;
  }

  void Set(int var)
  {
    *myVariable = var;
  }
  private:
  int* myVaraible;
 }

and the following code:

class ThreadB::QThread
{
  public:
  MyThreadB()
  {
  }
  void run()
  {
     myVariable = 10;
  }

  void Set(int var)
  {
     myVariable = var;
  }

  private:
  int myVaraible;
 }

I know the general theory of Mutexes, Race condition etc,

Assuming Set is always called after the thread is started, (i.e after a call to run()), Which thread owns "myVariable" in the execution of ThreadA and ThreadB ??

How does the main thread and QThread share resources in such a scenario ??

What is the scope and validity of myVariable within the QThread(i.e. ThreadA and ThreadB) and its main application ??

Thanks, Vishnu.

Was it helpful?

Solution

First of all, a QThread is not a thread. It's the manager/controller of a thread. A QThread object is always created in a thread that is different from the thread it is going to control.

Assuming both of your custom QThread objects are created in the main GUI thread, ThreadA::myVariable will be allocated in its own thread. While ThreadB::myVariable will be allocated in the main thread.

How you can share information between threads depends on the accesses you need from each threads. If it's always read by one thread and written by another, you should be able to get away with simple member access function. If it can be written by both threads, then a mutex lock is needed. QReadWriteLock provides a clear semantic and some optimization for that.

You can also use event and signal to send data across thread. The delivery of event is thread safe and with proper connection, so is signal.

OTHER TIPS

When using threads always keep in mind: All data is shared between the threads Thread programming (c/c++) is single data, multiple execution.

The is no definition of ownership of data to threads. All of a process' resources, which includes memory, may be accessed from every thread every time. Access to resources must be regulated by the programmer using encapsulation, mutexes, signal-slot decoupling etc

You probably know this and I don't want to sound patronizing. But telling which data in a program is never accessed from more than one thread and which data is (or might be) is the most crucial issue in multithread programming.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top