• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
3DModelerMan

Thread safe array

14 posts in this topic

I've been trying to learn about multithreaded programming and I came to an interesting problem. How would you make a thread safe array? Similar to the standard library's vector. I tried wrapping it in locks like this:
[source lang="cpp"]template <typename T>
class SafeArray : public IObject
{
public:

void pushBack(const T& obj)
{
m_lock.lock();
m_memory.push_back(obj);
m_lock.unlock();
}

void pushFront(const T& obj)
{
m_lock.lock();
m_memory.push_front(obj);
m_lock.unlock();
}

T popBack()
{
m_lock.lock();

T ret = m_memory.back();
m_memory.pop_back();

m_lock.unlock();

return ret;
}

///@brief This function attempts to pop an element from the back of the array. It returns false if the element couldn't be popped, and true otherwise.
bool tryPop(T& out)
{
if ( m_lock.tryLock() )
{
out = m_memory.back();
m_memory.pop_back();

m_lock.unlock();

return true;
}

return false;
}

///@brief Element access by index.
T operator[](int idx)
{
m_lock.lock();//Might be able to get rid of these locks
T ret = m_memory[idx];
m_lock.unlock();
return ret;
}

///@brief Attempts to access the object at the index.
///@param idx The index of the object you want to access
///@param obj A pointer to the object you wanted to access
///@return Returns false if the array was locked and could not be accessed
///in this case out will be set to NULL. True if the memory could be accessed.
bool tryAccess(int idx, T* out)
{
out = NULL;

if ( m_lock.tryLock() )
{
out = m_memory[idx];

m_lock.unlock();

return true;
}

return false;
}

///@brief Returns the size of the array.
///Don't use this to iterate over the array if elements might have been removed during iterating.
unsigned int size()
{
m_lock.lock();
unsigned int ret = m_memory.size();
m_lock.unlock();
return ret;
}

///@brief Deletes all elements in the array.
void clear()
{
m_lock.lock();
m_memory.clear();
m_lock.unlock();
}

///@brief Erases one element from the array at the given index.
void erase(int idx)
{
m_lock.lock();
m_memory.erase(m_memory.begin+idx);
m_lock.unlock();
}

///@return True if the array contains the value passed in. False Otherwise.
bool contains(T val)
{
bool ret=false;

m_lock.lock();

for (unsigned int i=0; i<m_memory.size(); ++i)
{
if ( m_memory[i] == val )
{
ret = true;
break;
}
}

m_lock.unlock();

return ret;
}

///@brief Searches through the array and removes the passed value.
///@param val The value to search the array for and remove.
///@return True if succesfull. False otherwise.
bool remove(T val)
{
bool ret=false;

m_lock.lock();

std::vector<T>::iterator i;
for (i = m_memory.begin(); i!=m_memory.end(); ++i)
{
if ( *i == val )
{
ret = true;
m_memory.erase(i);
break;
}
}

m_lock.unlock();

return ret;
}

private:

ThreadLock m_lock;

std::vector<T> m_memory;
};[/source]
But obviously that has major problems. If an object is added to the array, or removed from the array while a thread is iterating over it then it could end up causing problems. I know about thread safe queues and how they work (mostly). But if you have objects stored in an array that can't just be popped off of the queue every time you use them, what do you do? I did read something about an array that worked by keeping it's own internal array that threads just copied off of so that they could get kind of a snapshot of the array's contents at the time they copied, and the array could still be updated during other threads iterating.
0

Share this post


Link to post
Share on other sites
You could try to see how Intel TBB/Visual Studio 2012 has it done. It's huge mess of templates but concurrency::concurent_vector<> never failed me. push_back, pop_back, erase, iterators, nothing ever breaks.
0

Share this post


Link to post
Share on other sites
[quote name='Ripiz' timestamp='1350067545' post='4989550']
You could try to see how Intel TBB/Visual Studio 2012 has it done. It's huge mess of templates but concurrency::concurent_vector<> never failed me. push_back, pop_back, erase, iterators, nothing ever breaks.
[/quote]

Are you sure it has pop_back() and erase()? If they are implemented, they likely aren't thread-safe in any meaningful fashion. Many C++ lock-free 'vector's are implemented as ragged arrays, where each sub-array is twice as large as its predecessor (or similar). The other approach I've seen is a tree with a very high branch factor (e.g. 32).

Implementing concurrent element removal is fundamentally incompatible with these designs as far as I can tell, especially in C++ where value-based programming is the default.

There are also additional constraints on element types such as no-throw copy construction. Obviously there are other differences compared to regular vectors, such as non-contiguous elements (though locality is still good).

So, make sure you're using the container correctly!
0

Share this post


Link to post
Share on other sites
if a threat manipulates the array, thus poping, leavinbg freeing. You must asure it will not afect an other thread (maybe serving freed data)!

Lock the array in a thread by lock king word, that so thread will hang unless other thread leaves out its lock keyword block.

This way you sunchronize manupulation of data by threads paralel.
-1

Share this post


Link to post
Share on other sites
@Hodgman I'm trying to make sure that the objects in my scene graph can be accessed from other threads and have objects added to them. But I want to use locks as little as possible. Although, I guess adding child objects might be something that doesn't happen very often.

I don't ever use exceptions. I replaced my SafeArray with a queue class in all the places I could. I've got a thread pool system that uses it. It has a schedule function where you can schedule tasks that will be added to whichever thread's queue has the fewest. And then the worker thread just pops from the queue until it's empty then sleeps until it's woken for more work.
0

Share this post


Link to post
Share on other sites
If you don't use exceptions then your class has a fundamental problem: it has no way of reporting errors in the majority of your member functions. In that case you shouldn't be using std::vector as the underlying layer for your container as std::vector uses exceptions for it's error signalling. It's hard to call a container "safe" if you can't be sure any member function you call on it succeeded or not.
2

Share this post


Link to post
Share on other sites
[quote name='3DModelerMan' timestamp='1350138980' post='4989777']
@Hodgman I'm trying to make sure that the objects in my scene graph can be accessed from other threads and have objects added to them. But I want to use locks as little as possible. Although, I guess adding child objects might be something that doesn't happen very often.
[/quote]If objects can only be added, but not removed, then things are a bit simpler. You can allocate the new object from a thread-safe pool, initialize the new object, and then atomically set a pointer to it in the parent object.
...however, now if someone is iterating the graph at the same time that someone is adding nodes, it's random as to whether the new nodes will be iterated or not. So I'd still recommend you break your program into different passes/stages, e.g. a read stage and a modify stage. Edited by Hodgman
1

Share this post


Link to post
Share on other sites
Well if I break it up into different stages then wouldn't that be basically the same as having a serial program? Or do you mean something like: a node has a list of children, but when you call addChild it would instead add the child to another list that gets merged with the main "update" list in the beginning of the node's update function? And then I could do the same thing for removals too right? So any modifications to the list would be queued up and deferred until the beginning of the object's update, before any iterating was done in the frame. Or by breaking it into stages do you mean I need to radically alter the entire architecture of my engine?
0

Share this post


Link to post
Share on other sites
[quote name='3DModelerMan' timestamp='1350224511' post='4990038']
Well if I break it up into different stages then wouldn't that be basically the same as having a serial program? Or do you mean something like: a node has a list of children, but when you call addChild it would instead add the child to another list that gets merged with the main "update" list in the beginning of the node's update function? And then I could do the same thing for removals too right? So any modifications to the list would be queued up and deferred until the beginning of the object's update, before any iterating was done in the frame. Or by breaking it into stages do you mean I need to radically alter the entire architecture of my engine?
[/quote]Sorry I missed this reply.
Yes, queueing up modifications instead of performing them immediately is a good way to break up processing into several stages and reduce the amount of communication between threads.

Also, breaking algorithms into serial stages isn't the same as a serial program -- often many threads can contribute to each stage, and different threads can be working on different problems at the same time.
e.g. say we've got a single-threaded function, C, and two functions A & B that can be completed by parallel worker threads. Let's also say that A & B can also be split into 2 stages, and the code we're trying to execute looks like:
result = C( A(), B() )
Given 3 worker threads, their progress over time (vertical) could look like:
[code]#0 #1 #2
A1 A1 B1
B1 B1 A1
A2 A2 B2
B2 B2 A2
C .wait.[/code]
0

Share this post


Link to post
Share on other sites
I once read a wise statement on a forum saying that a container generally cannot make itself threadsafe on behalf of its client.

The thread safety generally needs to be done by the code using the container, because it inevitably needs to lock the container whilst performing more than one action with it. Thus this is a flawed endevaour, a "fool's errand" so to speak.
1

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0