Original Post
🔒 Locked
Thread safe streaming objects into world
Advertisement
Yeah that's a good idea - it's a kind of "message passing" between the threads.
It's not thread safe as you've written it. It is thread safe if you implement mutual exclusion - you've got to ensure that only one thread is touching the std::vector at a time. You can do this via Mutexes/Critical-sections. You lock the mutex/critical-section before doing anything that involves the vector, and then you unlock it afterwards.
Also, if 'addObject' does any processing (i.e. it's not really quick), you should do it while the mutex is unlocked, so that the other thread can access the vector during the call to 'addObject'. e.g.
It's not thread safe as you've written it. It is thread safe if you implement mutual exclusion - you've got to ensure that only one thread is touching the std::vector at a time. You can do this via Mutexes/Critical-sections. You lock the mutex/critical-section before doing anything that involves the vector, and then you unlock it afterwards.
Also, if 'addObject' does any processing (i.e. it's not really quick), you should do it while the mutex is unlocked, so that the other thread can access the vector during the call to 'addObject'. e.g.
while( true ){ lock mutex if( queue.empty() ) empty = true; else empty = false; item = queue.back() queue.resize( queue.size()-1 ) unlock mutex if( empty ) break; world->addObject( item );}
I think it wouldn't even run without multithreading. The queue.erase would screw up your index calculation. It might be a better choice to let the queue intact within the for loop and clear the whole thing afterwards.
I would also prefer pointers inside the vector, as it keeps down the overhead of copying things around.
Now about multithreading, no it is not safe. You need to guard the queue with a mutex. However, just throwing in mutexes easily slows down performance. If "latency" is not a problem, a double buffered queue might be a better choice. You create two queues, the streaming thread writes to the "front" queue, the game thread reads from the "back" queue and when the game thread is finished it will lock a mutex and switch both queues.
I would also prefer pointers inside the vector, as it keeps down the overhead of copying things around.
Now about multithreading, no it is not safe. You need to guard the queue with a mutex. However, just throwing in mutexes easily slows down performance. If "latency" is not a problem, a double buffered queue might be a better choice. You create two queues, the streaming thread writes to the "front" queue, the game thread reads from the "back" queue and when the game thread is finished it will lock a mutex and switch both queues.
Topic Locked
This topic has been locked by a moderator. New replies are not allowed.
Sign in to reply to this topic.
Advertisement