Std::thread questions - how to use?


Hey all,

I’m running into a bit of trouble figuring out how to use std::thread. I’m pretty sure I have it set up right, the issue is that when I go to compile, the separate thread seems to block the rest of the initialization of my app and I just see a white screen.

I’m basically setting it up like so

  // called in setup()	
  mThread = shared_ptr<thread>(new thread(bind(&Cube::update, this)));

In my threaded function

void update(){
    ci::ThreadSetup threadSetup;
     // do stuff here for infinity

I don’t need to be in sync with what OpenGL is doing I’m just trying to shift some math calculations over to another thread. Any ideas for why I’m running into problem?



Do you have the issue if you use a function other than update ?



assuming setup() is your application’s setup function, you’re binding a function from the Cube class, but this is pointing to your app.



Ah, i could have been a little more clear on that. The code was really more pseudo-code to keep things simple then what i actually have.

In this case setup() is refering to a setup function within Cube and im calling it from the main setup function in the app class.

Im away from the computer at the moment but i suddenly had a realization of what the issue might be. Could accidentally calling Cube::update at the same time(due to me testing an earlier revision of the class that i stupidly forgot to remove) as Cube::setup possibly be the issue?

I feel like thats the issue but it seems strange that that would block the rest of the application.


Well, if your Cube::update() contains a while( true ) {} and you’re calling it from the main thread, then sure it will hang. But if you’re only running Cube::update() on a separate thread, your main thread should not hang. To prevent problems, make Cube::update() a private member function.

A working sample that uses a background thread can be found here. I wouldn’t say this is an example of “best practice”, but maybe it will help. Although I think you already understand the basics pretty well.



ahhhhh gotcha, I’ll keep that in mind. Turns out that update() call I accidentally left in there was indeed the issue as the way I had it setup, that while loop was getting called on the main thread.

Doh! *smacks forehead:sweat_smile:

And thanks for the link too!