C++ (Qt) class MyThread : public QThread{ public:.... void addUserData(UserData *userData); protected: void run(); private: QMutex mutex_; QQueue<UserData *> listUserData_; // данные от основного потока };
C++ (Qt) .... void MyThread::addUserData(UserData *userData){ QMutexLocker locker(&mutex_); listUserData_.enqueue(userData); } void MyThread::run(){ UserData *userData; for (;;) { mutex_.lock(); userData= *listUserData_.begin(); listUserData_.dequeue(); mutex_.unlock(); ..... delete userData; .... }}
C++ (Qt) ... thread->addUserData(new UserData(/*data*/)); ...
C++ (Qt)class Thread : public QThread{public: Thread(); void run(); public slots: void sendData( const QString &str ); signals: void dataReaded( const QString &str ); private: QTcpSocket *m_socket;}; Thread::Thread(){ ... m_socket = new QTcpSocket; ...} void Thread::run(){ m_socket->moveToThread( this ); connect( m_socket, SIGNAL( readyRead() ), SLOT( readData() ) ); .... exec();} void Thread::sendData(...){ m_socket->write( .... );} void Thread::readData(){ m_socket->read( ... ); emit dataReaded(....);}
class tcpclient : public QThread{ Q_OBJECTpublic: tcpclient(); ~tcpclient();public slots: void sendData( const QString &str );signals: void recvData( const QString &str );private: QTcpSocket *m_socket; QString hostName; quint16 port;protected: void run();};tcpclient::tcpclient(){qDebug() << "Thread::constructor: " << QThread::currentThreadId();m_socket = new QTcpSocket;start();}tcpclient::~tcpclient(){}void tcpclient::run(){ qDebug() << "Thread::run: " << QThread::currentThreadId(); m_socket->moveToThread( this ); connect( m_socket, SIGNAL( readyRead() ), SLOT( readData() ) ); hostName = "test.ru"; port = 5000; m_socket->connectToHost(hostName, port); exec();}void tcpclient::readData(){ qDebug() << "WorkerReadData: " << QThread::currentThreadId();}void tcpclient::sendData(const QString &str){ qDebug() << "WorkerSendData: " << QThread::currentThreadId(); m_socket->write("hi");}Далее в мейн треде создал объект:tcpclient worker;connect(this, SIGNAL(sendData(const QString &str )),worker, SLOT(sendData(const QString &str )));
C++ (Qt)threadSocket->moveToThread(threadSocket);