0

I have a thread class that works nice on desktop but crashes on android. In my Qt application I need a task with a shared object like this:

class UpdateTask : public QRunnable
{
    MyPointer * _p;
    void run()
    {
        qDebug() << "Hello world from thread" << QThread::currentThread();
        _p.write();
        qDebug() << "Hello3 world from thread" << QThread::currentThread();
    }
public:
    UpdateTask ();
    ~UpdateTask ();
    void setPointer(MyPointer * pointer){
        _p = pointer;
    }
};

In main I want to be able to run the Task as follows:

UpdateTask * task = new UpdateTask ();
task->setPointer(_pointer);
QThreadPool::globalInstance()->start(task);

This works prefectly in desktop. But in android as you may know it does not work. when I run it Fatal signal 11 (SIGSEGV), code 1, fault addr 0x98 in tid 31727 (Thread (pooled)) occurs and only the first Hello prints before using the _p
So my question is this:
How Can I use MyPointer (a shared object) in all threads. It is not possible for me to pass a copy of it to each thread. It should be passed by pointer in all threads. In other words How could I use a shared object in all threads. In methods that are not const and each of the threads could change the object.
I know there are several techniques to handle multi-threded applications in Qt. which one is suitable for working on an android device?
Do I need to use JNI for safe multithreading in android? I guess I do!

a.toraby
  • 3,232
  • 5
  • 41
  • 73

1 Answers1

2

Make it threadsafe by wrapping access to your pointer with a mutex or semaphore or something else.

An alternative is to send it using a Queued signal slot connection.

Here is one way to do it with a Mutex:

// Member variable of UpdateTask
QMutex m_mutex;
// In your constructor
_p = 0;

void UpdateTask::setPointer(MyPointer *pointer)
{
    QMutexLocker locker(&m_mutex);
    _p = pointer;
}

void UpdateTask::run()
{
    // Create connections here, and the thread affinity will be correct, 
    // otherwise you need to use moveToThread() or explicitly say a 
    // Qt::QueuedConnection


    // Any place where _p is accessed
    {
        QMutexLocker locker(&m_mutex);
        if(p != 0)
            p->write();
    }
}

http://doc.qt.io/qt-5/qmutexlocker.html#details

Hope that helps.

phyatt
  • 18,472
  • 5
  • 61
  • 80
  • Thanks for your answer. But I tested the application on desktop and it works nice without Mutex. The problem is android. The Mutex didn't fix the problem. – a.toraby Mar 15 '15 at 06:11