• 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
vNeeki

Threading question

2 posts in this topic

Hello!

I'm using threads for the first time , and im making use of SDL's threading functions which are easy and i've got everything working perfectly...or at least that's what i believe , which is what gave me the motivation to ask if im doing everything properly.



This is a sample unit test which simulates the behaviour of the task by 99,9% :

[code]

SomeDynamicBlock** data;
int data_ptr,data_len;

int WorkWorkWork(void* data)
{
unsigned int oldTime = 0;

while (true)
{
if (SDL_GetTicks() - oldTime > 1000)
{
for (int i = 0,j = data_ptr;i < j;i++)
{
if (data[i])
data[i]->Update(SDL_GetTicks());
}
oldTime = SDL_GetTicks();
}
}
return 0;
}

bool SetupWorker(int size)
{
//Only happens once!
data = new SomeDynamicBlock*[size];
data_ptr = 0;
data_len = size;

for (int i = 0;i < data_len;i++)
data[i] = 0;

sdl_work_thread = CreateThread(WorkWorkWork);
return true;
}

void KillWorker()
{
SDL_KillThread(sdl_work_thread);
delete data;
data = 0;
}

bool AddRef(SomeDynamicBlock* shared)
{
if (data_ptr < data_len)
{
data[data_ptr++] = shared;
return true;
}

for (int i = 0;i < data_ptr;i++)
{
if (!data[i])
{
data[i] = shared;
return true;
}
}
return false;
}

[/code]

And these are my questions :

A.What do you think of AddRef ? Shouldn't i suspend the thread at that time ? If so how would i do it ?
B.Is SDL_GetTicks() thread safe ?

Thanks for any help.
0

Share this post


Link to post
Share on other sites
[quote]
A.What do you think of AddRef ? Shouldn't i suspend the thread at that time ? If so how would i do it ?
[/quote]
AddRef is not thread safe. Pre C++0x versions of C++ lack a standard threading model, so you cannot rely on writes being either atomic or immediately published to all cores.processors.

A minimal change would be to introduce a global mutex, which is locked in before any thread reads or writes this data, and unlocked when the reading/writing completes. Such locking will effectively serialize access to that code. Unless you introduce fine grained locking, your overall program acts in a serial fashion, and your multi-threaded solution can actually become slower than a single-threaded implementation.

A better solution would be to re-architect the problem in a thread-friendly manner. For example, the producer/consumer pattern. Thread friendly solutions attempt to minimise the frequency and duration of synchronisation events, such as locking.

There are two broad, common approaches. The first is to aggressively copy any data that needs to be shared between threads. The owner thread builds a copy of the data required for a given task, and then the worker thread(s) gets exclusive write or shared read access to this data. Another is hand-off, the owner thread reserves some memory for the task, and gives the worker thread(s) exclusive write access to the memory. While the task is ongoing, the owner does not access the task data (save perhaps polling some thread-safe status or result queue). When the worker completes, it publishes its result somewhere and relinquishes access to the task memory.

The key to high performance threading is to totally minimise the amount of communication between threads. Even having two different variables written in different threads can cause performance issues, due to large cache lines and false sharing.

[quote]
B.Is SDL_GetTicks() thread safe ?
[/quote]
It isn't documented as being thread safe. Indeed, looking at the [url="http://svn.libsdl.org/tags/SDL/release-1.2.14/src/timer/"]SDL 1.2.14 source code[/url], there appears to be a race condition in the first call to SDL_GetTicks() on macos platforms.

You didn't ask this, but you should't call SDL_KillThread(). Killing a thread can cause deadlocks. If thread A kills thread B, and thread B holds a lock that thread A later tries to acquire, your program will fail to make progress and the user will likely be forced to manually intervene to halt the process.

A better solution is co-operative shut down. For example thread periodically polls some kind of thread safe shut down flag. The "master" thread sets this flag, and waits some multiple of the polling interval until all threads have exited. If the threads are taking too long, then you might think about killing them. However, it is usually easier to just ask the O.S. to terminate the process, as that will avoid race conditions and bugs in your kill logic which could likewise hang the process.
1

Share this post


Link to post
Share on other sites
[quote name='rip-off' timestamp='1328226720' post='4908906']
[quote]
A.What do you think of AddRef ? Shouldn't i suspend the thread at that time ? If so how would i do it ?
[/quote]
AddRef is not thread safe. Pre C++0x versions of C++ lack a standard threading model, so you cannot rely on writes being either atomic or immediately published to all cores.processors.

A minimal change would be to introduce a global mutex, which is locked in before any thread reads or writes this data, and unlocked when the reading/writing completes. Such locking will effectively serialize access to that code. Unless you introduce fine grained locking, your overall program acts in a serial fashion, and your multi-threaded solution can actually become slower than a single-threaded implementation.

A better solution would be to re-architect the problem in a thread-friendly manner. For example, the producer/consumer pattern. Thread friendly solutions attempt to minimise the frequency and duration of synchronisation events, such as locking.

There are two broad, common approaches. The first is to aggressively copy any data that needs to be shared between threads. The owner thread builds a copy of the data required for a given task, and then the worker thread(s) gets exclusive write or shared read access to this data. Another is hand-off, the owner thread reserves some memory for the task, and gives the worker thread(s) exclusive write access to the memory. While the task is ongoing, the owner does not access the task data (save perhaps polling some thread-safe status or result queue). When the worker completes, it publishes its result somewhere and relinquishes access to the task memory.

The key to high performance threading is to totally minimise the amount of communication between threads. Even having two different variables written in different threads can cause performance issues, due to large cache lines and false sharing.
[/quote]

Thanks for sharing the knowledge.I think i will pick your local buffer approach which sounds very easy to implement.


[quote name='rip-off' timestamp='1328226720' post='4908906']
[quote]
B.Is SDL_GetTicks() thread safe ?
[/quote]
It isn't documented as being thread safe. Indeed, looking at the SDL 1.2.14 source code, there appears to be a race condition in the first call to SDL_GetTicks() on macos platforms.
[/quote]

Got it!
I will make sure to call SDL_GetTicks() just before the thread gets spawned.

[quote name='rip-off' timestamp='1328226720' post='4908906']
You didn't ask this, but you should't call SDL_KillThread(). Killing a thread can cause deadlocks. If thread A kills thread B, and thread B holds a lock that thread A later tries to acquire, your program will fail to make progress and the user will likely be forced to manually intervene to halt the process.

A better solution is co-operative shut down. For example thread periodically polls some kind of thread safe shut down flag. The "master" thread sets this flag, and waits some multiple of the polling interval until all threads have exited. If the threads are taking too long, then you might think about killing them. However, it is usually easier to just ask the O.S. to terminate the process, as that will avoid race conditions and bugs in your kill logic which could likewise hang the process.
[/quote]

Thanks for all these priceless hints , i will start implementing everything from scratch a-s-a-p.

[code]
++++++++rep; + bookmarked.
[/code]
0

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