Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Threads not running in parallel  (Read 11170 times)

0 Members and 2 Guests are viewing this topic.

Ixrec

  • Hero Member
  • *****
  • Posts: 1241
    • View Profile
    • Email
Re: Threads not running in parallel
« Reply #15 on: May 03, 2014, 11:56:49 pm »
Put your objects in the correct scope so they live as long as you want them to.  This is an important principle for C++ code in general, not just for using resource objects like threads.  You need to understand when objects' constructors and destructors get called, and what they do.

Your Server object should be created in main(), before the main loop begins.

The Server's sf::Thread should be a member variable that gets initialized in the constructor and launched in a method, NOT a local variable that gets created, initialized, launched and destroyed all in the constrcutor.

Walta69

  • Newbie
  • *
  • Posts: 30
    • View Profile
Re: Threads not running in parallel
« Reply #16 on: May 04, 2014, 12:01:48 am »
I have done all of the above:

void Server::StartThread()
{
   serverThread = new std::thread(&Server::test, this);
   serverThread->join();
}

which gets called in the main as follows:

int main()
{
   Server * server;
   server = new Server(8080); // start server
...
...
...
            else if (e.key.code == sf::Keyboard::S)
            {
               if (!hasChosen)
               {
                  hasChosen = true;
                  std::cout << "Test";
                  server->StartThread();
               }
            }
...
...
...

Ixrec

  • Hero Member
  • *****
  • Posts: 1241
    • View Profile
    • Email
Re: Threads not running in parallel
« Reply #17 on: May 04, 2014, 12:07:39 am »
join() waits for the thread to finish.  I don't think you want to call that in StartThread().

Walta69

  • Newbie
  • *
  • Posts: 30
    • View Profile
Re: Threads not running in parallel
« Reply #18 on: May 04, 2014, 12:11:49 am »
I am a retard.

Walta69

  • Newbie
  • *
  • Posts: 30
    • View Profile
Re: Threads not running in parallel
« Reply #19 on: May 04, 2014, 12:12:17 am »
Thank you :O

Ixrec

  • Hero Member
  • *****
  • Posts: 1241
    • View Profile
    • Email
Re: Threads not running in parallel
« Reply #20 on: May 04, 2014, 12:14:18 am »
Phew, glad you finally got it to work.