C ++线程块主线程

时间:2017-09-07 16:21:28

标签: c++ multithreading std boost-thread

问题:当ExecuteQueue函数被调用时,队列中已有两个现有的数据包,并且它们被正确调用(打印到控制台)。但即使ExecuteQueue函数在另一个Thread中循环,主线程也会被阻塞(它永远不会到达QueuePacket)。

我已经浏览过stackoverflow,而且大多数问题都与.join有关,但这个问题可能并非如此(删除.join没有任何区别)。

Main.cpp的

int main() { 
    // Start Client
    boost::thread tClient(&Networking::Client::Initialize, Networking::Client()); // Still in Main-Thread???!?!?
    Networking::Client::QueuePacket(Networking::Packet::Types::Disconnect);

    // Start Modules
    tClient.join();
    return 0;
}

Client.cpp (仅限必要的功能)

    static bool QueuePacket(Packet p) { // Pushes existing Packet
        return Globals::Queue.push(p);
    }

    void ExecuteQueue() {
        while (Client::Active && Globals::NetworkConnectivity) {
            if (Globals::Queue.empty()) { Sleep(500); continue; }

            Packet p(Packet::Types::Invalid);
            if (!Globals::Queue.pop(p)) continue; // Copies Packet into p on Success
            if (p.Type == Packet::Types::Disconnect) { Client::Active = false; } // Disconnects Queue
            if (p.Type == Packet::Types::Invalid) { } // Find some error handling here

            ExecutePacket(p);
        }
    }

1 个答案:

答案 0 :(得分:0)

    Networking::Client* ClientPtr = new Networking::Client();
    boost::thread tClient(&Networking::Client::Initialize, ClientPtr);

这很有效。