-1

I create some class like this:

class TcpClient: public QObject
{
    public TcpClient(){}
    QSocket *socket;

    QMutex mutex;

    void write()
    {
        QMutexLocker locker(&mutex);
        socket->write();
    }
}

class SubQthread :public QThread
{
    public:
    SubQthread(TcpClient *tcp)
    {
        //
        m_tcp = tcp;

    }
    private:
    TcpClient *m_tcp;
    protected:
    void run()
    {
        m_tcp->write();
    }

}


class Widget:public QWidget
{
    public:
    Widget()
    {
        client =  new TcpClient(this);


    }
    private:
    TcpClient *client;


}

When I create multiple sub-QThreads, I pass the pointer TcpClient* to QThread. Is this a good idea? On the condition that i can ensure TcpClient* will be deleted after the app finished.

Simon Kraemer
  • 5,700
  • 1
  • 19
  • 49
M.Joe
  • 11
  • 1
  • 3
  • Having multiple threads communicating through the same socket is generally a bad idea, even with locking. What is your use-case? Why do all the threads need to use the same socket? Can't you have one socket and one connection *per thread*? – Some programmer dude Feb 23 '16 at 15:36
  • 1
    I think this belongs to Code Review – Victor Feb 23 '16 at 15:38

2 Answers2

1

There are multiple issues in your codes that should be addressed.

  • There is no QSocket class in Qt framework. I presume you are using QTcpSocket.

  • QTcpSockets cannot be used across multiple threads. Only their creating threads can call their methods.

  • The mutex object should be shared across all threads.

If you want to implement a communication channel between multiple threads, suggestions are:

  • QSharedMemory.
  • Signal/slot for small amount of data.
  • Manually implementing shared variables protected by mutexes.
  • Event loops.
frogatto
  • 28,539
  • 11
  • 83
  • 129
0
  1. QTcpSocket object (and each other object of QObject derived class) lives in a thread where it was created. If you create QTcpSocket object in main (GUI) thread and want that it lives in another thread, you should use QObject::moveToThread method: qt thread with movetothread. But the right way is create socket just in working thread or use creating in necessary thread by using socket descriptor: QAbstractSocket::setSocketDescriptor()
  2. You should be sure that you call your QTcpSocket object from the same thread that it lives. For this purpose you can use Signals & Slots with Qt::QueuedConnection
Vladimir Bershov
  • 2,701
  • 2
  • 21
  • 51
  • thank you very much! I have understood your meaning,meanwhile,thanks for bearing my bad English – M.Joe Feb 24 '16 at 00:47
  • @M.Joe, See also: [what is the correct way to implement a `QThread`](https://stackoverflow.com/questions/4093159/what-is-the-correct-way-to-implement-a-qthread-example-please) and http://stackoverflow.com/a/35056527/4149835 – Vladimir Bershov Feb 24 '16 at 02:46