main和thread函数中的不同套接字描述符

时间:2015-10-15 12:00:53

标签: c++ multithreading sockets

我的主要功能代码如下所示

 if (argc < 2 || argc > 4)
    {
        printf("usage: server <port> [<ip>]\n");
        exit(1);
    }

    TCPStream* stream = NULL;
    TCPAcceptor* acceptor = NULL;
    if (argc == 3)
    {
        acceptor = new TCPAcceptor(atoi(argv[1]), argv[2]);
    }
    else
    {
        acceptor = new TCPAcceptor(atoi(argv[1]));
    }

    if (acceptor->start() == 0)
    {
        while (1)
        {
            stream = acceptor->accept();
            if (stream != NULL)
            {
                /*
                ssize_t len;
                char line[256];
                while ((len = stream->receive(line, sizeof(line))) > 0) {
                    line[len] = 0;
                    printf("received - %s\n", line);
                    stream->send(line, len);
                    */
                cout << "in main" << stream->getsockdescriptor() << endl;
                pthread_t sniffer_thread;
                if( pthread_create( &sniffer_thread, NULL, connection_handler, (void*)&stream) < 0)
                {
                     perror("could not create thread");
                     return 1;
                }
                //Now join the thread , so that we dont terminate before the thread
                pthread_join( sniffer_thread , NULL);
             }
                delete stream;
          }
       }
    exit(0);
}

和线程功能代码如下所示

void *connection_handler(void * args)
{
    TCPStream *stream = (TCPStream *)args;
    ssize_t len;
    char line[256];
    cout << "check1" << endl;
    cout << stream->getsockdescriptor() << endl;
    while ((len = stream->receive(line, sizeof(line))) > 0)
    {
        cout << "check2" << endl;
        line[len] = 0;
        printf("received - %s\n", line);
        stream->send(line, len);
    }

}

即使我将对象传递给线程函数。我得到不同的文件描述符值。 在main中它显示正确.Start(),Accept(),receive()是包装函数

1 个答案:

答案 0 :(得分:0)

问题是pthread_create调用以及你在那里传递的参数:

pthread_create( &sniffer_thread, NULL, connection_handler, (void*)&stream)

这里不传递指向TCPStream对象(即TCPStream*)的指针,而是指向指向TCPStream对象的指针(即TCPSTream**

这将导致线程函数中的未定义行为,因为您将指针视为指向TCPStream的指针。

在调用&时,只需删除地址操作符pthread_create即可开始工作。