Home Forums C Programming multithreading on OSX

Viewing 1 reply thread
  • Author
    Posts
    • #2109
      si_icarus
      Participant

      Hi all, I have a query about multithreading. What I would like to do is, at the start of my main update() function, start a couple of threads in parallel, once they are all complete carry on with my main update function.

      I am having trouble getting this working the way I want. I don’t want my threads to loop continuously independent of my main update loop, I want them all to start at the beginning of my update loop, and then once they are all finished, feed the data around, then render, then repeat.

      I tried creating a thread every update loop which runs only once (no while() in the function) – it works and behaves fine for a few minutes, then the threads just stop being created – no crash or hang, just no updates from threads. I also tried using an infinte while() but with a flag that determined whether the code ran that frame or not, and only set that flag at the beginning of the main update loop (code for this below) – that one is very stable, but behaviour was weird, I think the thread updates weren’t being called when I wanted them to.

      I’ve read a lot of documentation on multithreading in general and all the pthread commands. I understand the fundamentals of protecting data and all that.. but I’m just lacking a lot of experience and strategy .. so any suggestions welcome!

      This is my thread class I’m using which has the infinite loop in the threaded function, but runs the update function if the flag is set. I initialize the flag at the beginning of each main update with thread1->runOnce(); thread2->runOnce(); etc…. but it doesn’t run smoothly.

      and it’s based on this OpenFrameworks class:

    • #3404
      si_icarus
      Participant

      Actually, I think I’ve actually identified the problem. I think it was the sleep() function in my thread loop. I understand why I need that if the loop is continuously running and doing heavy stuff, but do I need it in my case?

      When I comment out the sleep line (As below), the behaviour looks a lot smoother and correct, maybe because as soon as I set the bHasRunThisFrame flag in the thread instance to false, the update function is called almost immediately (which is what I want), whereas with the sleep() function, maybe there was a delay of upto interval before the update kicked in?…. or something :P Is it bad to not have a sleep function in there?

      // run the update function in another thread

Viewing 1 reply thread
  • The forum ‘C Programming’ is closed to new topics and replies.