0

我有一个线程类在桌面上运行良好,但在 android 上崩溃。在我的 Qt 应用程序中,我需要一个具有如下共享对象的任务:

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;
    }
};

主要我希望能够按如下方式运行任务:

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

这在桌面上非常有效。但是在你可能知道的android中它不起作用。当我运行它Fatal signal 11 (SIGSEGV), code 1, fault addr 0x98 in tid 31727 (Thread (pooled))时,在使用 _p 之前只有第一个 Hello 打印
所以我的问题是:
如何在所有线程中使用 MyPointer(共享对象)。我不可能将它的副本传递给每个线程。它应该在所有线程中通过指针传递。换句话说,我如何在所有线程中使用共享对象。在不是 const 的方法中,每个线程都可以更改对象。
我知道有几种技术可以在 Qt 中处理多线程应用程序。哪一个适合在安卓设备上工作?
我是否需要使用 JNI 在 android 中进行安全的多线程处理?我想我会的!

4

1 回答 1

2

通过使用互斥锁或信号量或其他东西包装对指针的访问,使其成为线程安全的。

另一种方法是使用 Queued 信号槽连接发送它。

这是使用互斥锁的一种方法:

// 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

希望有帮助。

于 2015-03-14T14:05:03.740 回答