Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > С/С++: Кроссплатформенное программирование, Qt/Gtk+/wxWidgets > [qt4]Посылка сигналов между потоками


Автор: BiTOk 11.5.2011, 18:39
Доброе время суток. Встала задача написания двухпоточной программы: один отвечает за интерфейс, второй за непрерывный процесс моделирования некой системы. Данные для моделирования вводятся в главном потоке - в потоке интерфейса, работа с ними идёт во втором потоке. При работе второго потока необходимо передавать некоторые данные для вывода на форму в первый поток. Если я организую передачу этой информации с помощью сигналов-слотов, то где будет работать соответствующий слот, если сигнал послан из потока №2? Как лучше организовать структуру такой программы?

Автор: Artemon 11.5.2011, 20:14
Цитата(BiTOk @  11.5.2011,  18:39 Найти цитируемый пост)
где будет работать соответствующий слот, если сигнал послан из потока №2? 

По-умолчанию В потоке #1

Автор: BiTOk 11.5.2011, 20:17
Откуда такие умолчания и как их изменить?
ADD
Какую литературу можно почитать по таким тонкостям? В хелпе ответ на вышепоставленный вопрос найден не был.

Автор: Artemon 11.5.2011, 20:35
Код

bool QObject::connect ( const QObject * sender, const char * signal, const QObject * receiver, const char * method, Qt::ConnectionType type = Qt::AutoConnection )


В методе QObject::connect() последний параметр отвечает за тип соединения, вот описание этого параметра:

Код

enum Qt::ConnectionType

This enum describes the types of connection that can be used between signals and slots. In particular, it determines whether a particular signal is delivered to a slot immediately or queued for delivery at a later time.Constant    Value    Description
Qt::AutoConnection    0    (default) If the signal is emitted from a different thread than the receiving object, the signal is queued, behaving as Qt::QueuedConnection. Otherwise, the slot is invoked directly, behaving as Qt::DirectConnection. The type of connection is determined when the signal is emitted.
Qt::DirectConnection    1    The slot is invoked immediately, when the signal is emitted.
Qt::QueuedConnection    2    The slot is invoked when control returns to the event loop of the receiver's thread. The slot is executed in the receiver's thread.
Qt::BlockingQueuedConnection    4    Same as QueuedConnection, except the current thread blocks until the slot returns. This connection type should only be used where the emitter and receiver are in different threads. Note: Violating this rule can cause your application to deadlock.
Qt::UniqueConnection    0x80    Same as AutoConnection, but the connection is made only if it does not duplicate an existing connection. i.e., if the same signal is already connected to the same slot for the same pair of objects, then the connection will fail. This connection type was introduced in Qt 4.6.
Qt::AutoCompatConnection    3    The default type when Qt 3 support is enabled. Same as AutoConnection but will also cause warnings to be output in certain situations. See Compatibility Signals and Slots for further information.


Добавлено через 9 минут и 46 секунд
Если поставишь Qt::DirectConnection, то слот будет выполняться в потоке, который сделал emit
Если поставишь Qt::QueuedConnection, то слот будет выполняться в потоке,  в котором определен слот.

Автор: borisbn 12.5.2011, 08:53
Цитата(BiTOk @  11.5.2011,  20:17 Найти цитируемый пост)
Какую литературу можно почитать по таким тонкостям? В хелпе ответ на вышепоставленный вопрос найден не был.

http://doc.qt.nokia.com/4.7-snapshot/threads-qobject.html#signals-and-slots-across-threads

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)