• ### Announcements

• #### Download the Game Design and Indie Game Marketing Freebook07/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.
Followers 0

# [SDL] Threads very slow? Is it my code or is this normal?

## 8 posts in this topic

I'm using SDL for graphics and threading. Basically I have one thread processing/generating information and saving the information to a file, and another thread reading information from those same files and playing the information back to the user. For some reason, if I have both threads running at the same time, they both run painfully slow. However if I run only one part of the program at once it runs pretty quickly.

There is no interaction between the threads whatsoever, except through files. The playback thread naturally runs slower than the other thread (at 10 ticks per second, while the generation thread has no cap) so it only needs to access files every several seconds, and the generation thread is always way ahead. In other words there's never a situation where both threads are fighting for file handle access.

I'm thinking it has something to do with both threads having tight loops. I read something about threading in C++11 where it always runs instructions from each thread in parallel, so basically thread B's speed is cut in half by thread A's "while (true) {}" loop code. I could use SDL_Delay() instead of a timer but thread A is the user interface and I don't want to freeze the whole screen and block user input.

What am I doing wrong?

// PLAY BACK THREAD LOOP (THREAD A)
while (true)
{
process_user_input();
if (is_time_for_next_frame())
{
if (has_frames_loaded()) playback_next_frame();
else read_frame_queue_from_file();
}
}

// PROCESSING THREAD LOOP (THREAD B)
while (true)
{
generate_frame();
push_frame_to_queue();

if (queue_is_full())
save_queue_to_file();
}


0

#### Share this post

##### Share on other sites

Is there a reason for using the filesystem to do your communication here? Files will eventually hit the disk (though buffering might hide this in some cases), and the disk is slow, by orders of magnitude over even uncached memory accesses. If one thread is trying to read data from one area of the disk, and another thread is writing data to a different part of the disk, one thread is going to be waiting for the disk heads to seek.

There are other options, if persisting the data is not an actual requirement.

1

#### Share this post

##### Share on other sites

Is there a reason for using the filesystem to do your communication here? Files will eventually hit the disk (though buffering might hide this in some cases), and the disk is slow, by orders of magnitude over even uncached memory accesses. If one thread is trying to read data from one area of the disk, and another thread is writing data to a different part of the disk, one thread is going to be waiting for the disk heads to seek.

There are other options, if persisting the data is not an actual requirement.

The generation thread is constantly making new files. The playback thread only needs to load files when it starts and then once every few minutes, and when it loads them it makes sure it loads every file available at the time (well, it has a cache limit, but it's pretty large). In other words the playback thread is idle disk-wise 99% of the time and it becomes less and less disk dependent as it runs since more and more files are loaded each time it hits the end of current playback. I thought it could be a disk access problem at first too so I made sure I wasn't making any dumb moves.

Edited by Nüb?ek Pænus
0

#### Share this post

##### Share on other sites

Is there a reason for using the filesystem to do your communication here? Files will eventually hit the disk (though buffering might hide this in some cases), and the disk is slow, by orders of magnitude over even uncached memory accesses. If one thread is trying to read data from one area of the disk, and another thread is writing data to a different part of the disk, one thread is going to be waiting for the disk heads to seek.

There are other options, if persisting the data is not an actual requirement.

The generation thread is constantly making new files. The playback thread only needs to load files when it starts and then once every few minutes, and when it loads them it makes sure it loads every file available at the time (well, it has a cache limit, but it's pretty large). In other words the playback thread is idle disk-wise 99% of the time and it becomes less and less disk dependent as it runs since more and more files are loaded each time it hits the end of current playback. I thought it could be a disk access problem at first too so I made sure I wasn't making any dumb moves.

Getting thread A to sleep a little (even just a couple of milliseconds per loop) should improve things without negatively affecting the input processing, but I don't think that this can entirely explain your performance problems (especially if you're running on a multi-core machine).

How are you loading every file available on your playback thread? If you're asking the file system which files are available, then that's also a file system operation that may be hitting the disk resource. Do you have a mechanism to make sure you're not going to try to load a file that the file creator thread is still writing?

I'm pretty sure the problem has to lie with the disk access in some way or another. Perhaps you need a system where the newest written files are cached in memory and the reading thread can grab them from memory instead of the disk. Or maybe something simple would work, like create a mutex which the threads must have locked before they're allowed to do any disk access (including asking the file system what files exist).

One more thing, how small/numerous are the files you're generating? Possibly you might improve matters by having fewer, larger files.

0

#### Share this post

##### Share on other sites

Is there a reason for using the filesystem to do your communication here? Files will eventually hit the disk (though buffering might hide this in some cases), and the disk is slow, by orders of magnitude over even uncached memory accesses. If one thread is trying to read data from one area of the disk, and another thread is writing data to a different part of the disk, one thread is going to be waiting for the disk heads to seek.

There are other options, if persisting the data is not an actual requirement.

The generation thread is constantly making new files. The playback thread only needs to load files when it starts and then once every few minutes, and when it loads them it makes sure it loads every file available at the time (well, it has a cache limit, but it's pretty large). In other words the playback thread is idle disk-wise 99% of the time and it becomes less and less disk dependent as it runs since more and more files are loaded each time it hits the end of current playback. I thought it could be a disk access problem at first too so I made sure I wasn't making any dumb moves.

Getting thread A to sleep a little (even just a couple of milliseconds per loop) should improve things without negatively affecting the input processing, but I don't think that this can entirely explain your performance problems (especially if you're running on a multi-core machine).

How are you loading every file available on your playback thread? If you're asking the file system which files are available, then that's also a file system operation that may be hitting the disk resource. Do you have a mechanism to make sure you're not going to try to load a file that the file creator thread is still writing?

I'm pretty sure the problem has to lie with the disk access in some way or another. Perhaps you need a system where the newest written files are cached in memory and the reading thread can grab them from memory instead of the disk. Or maybe something simple would work, like create a mutex which the threads must have locked before they're allowed to do any disk access (including asking the file system what files exist).

One more thing, how small/numerous are the files you're generating? Possibly you might improve matters by having fewer, larger files.

Hmm. Yeah it has to be a file system issue. I'll modify my program to be able to run only ONE thread per application instance and then run two instances of the program side by side, just to make sure, then I'll post results. Thanks!

0

#### Share this post

##### Share on other sites

The generation thread is constantly making new files. The playback thread only needs to load files when it starts and then once every few minutes, and when it loads them it makes sure it loads every file available at the time (well, it has a cache limit, but it's pretty large). In other words the playback thread is idle disk-wise 99% of the time and it becomes less and less disk dependent as it runs since more and more files are loaded each time it hits the end of current playback. I thought it could be a disk access problem at first too so I made sure I wasn't making any dumb moves.

Ok, that is more an overview of what you're doing, I still don't understand what you're trying to achieve, and why you think that using the filesystem is the best mechanism.

Have you considered other communication mechanisms, for example using a socket or a pipe? These can act as a way to control the relative speeds of a producer and consumer, as the producer will block once it fills the buffer, and the consumer will block until there is data in the buffer.

Another approach is to utilise the shared address space. You can use SDL's atomics or synchronisation primitives such as mutexes or semaphores to control access to a shared data structure.

It seems like an odd design in a single process for one thread to write the data to the filesystem, and another to read it all back more or less immediately, when there are far more direct ways of moving data between the two threads.Of course, if persisting the data is necessary, then there are different considerations, but I still think you might be able to avoid a round trip to the disk.

0

#### Share this post

##### Share on other sites

The generation thread is constantly making new files. The playback thread only needs to load files when it starts and then once every few minutes, and when it loads them it makes sure it loads every file available at the time (well, it has a cache limit, but it's pretty large). In other words the playback thread is idle disk-wise 99% of the time and it becomes less and less disk dependent as it runs since more and more files are loaded each time it hits the end of current playback. I thought it could be a disk access problem at first too so I made sure I wasn't making any dumb moves.

Ok, that is more an overview of what you're doing, I still don't understand what you're trying to achieve, and why you think that using the filesystem is the best mechanism.

Have you considered other communication mechanisms, for example using a socket or a pipe? These can act as a way to control the relative speeds of a producer and consumer, as the producer will block once it fills the buffer, and the consumer will block until there is data in the buffer.

Another approach is to utilise the shared address space. You can use SDL's atomics or synchronisation primitives such as mutexes or semaphores to control access to a shared data structure.

It seems like an odd design in a single process for one thread to write the data to the filesystem, and another to read it all back more or less immediately, when there are far more direct ways of moving data between the two threads.Of course, if persisting the data is necessary, then there are different considerations, but I still think you might be able to avoid a round trip to the disk.

I apologize for the lack of posts. I've been hard at work at reworking the system to make it work with less dependency on the filesystem (among other things that were broken).

Basically what I have now is:

• PLAYBACK thread requests information from a global (cross-thread) class (let's call it Timeline)
• GENERATION thread pushes information to the Timeline as it becomes available
• TIMELINE thread takes care of saving and writing data - it reads previously saved data when it seems like it might be requested soon, and it saves cached data when the buffer is near full. (Actually the timeline thread is currently disabled for debugging)

As before, the playback thread can be sped up or slowed down while the generation thread runs at full speed.

The system works fine as long as I keep the playback speed to default, however I start having problems when I run it at higher speeds. The faster it goes the higher the chance of a deadlock on either thread's part. When one thread crashes, the other continues as if nothing had happened, so it's not a regular deadlock where both threads wait for the other to finish.

I've tried with and without mutexes, but this changes nothing. I added in printf() statements before and after every mutex lock/unlock call and the output looks as it should. Then I added printf() statements in the playback thread (the one most likely to freeze) to track down exactly where it freezes but it simply stops after a certain function call. For example:

void func1()
{
printf("func1() was called"); fflush(stdout);
func2();
// code for func1 goes here
}

void func2()
{
printf("func2() was called"); fflush(stdout);
// code for func2 goes here
}


I get the func1() confirmation but not the func2() confirmation, meaning the thread stops running at the moment func2() gets called. I have several instances of this scenario all around my code now, so it's not just that particular piece of code. This can happen at any time, and it's always right after a function gets called. It just freezes. Also note how I added fflush() calls after each printf() call to make sure it gets written to the file.

I can't debug this because, well, it doesn't crash so my regular debugger (Dev-C++) doesn't inform me of anything. I tried running GDB from the command line but GDB freezes as well, at the start of the program. It does the usual "new thread at [0xblablabla]" but then it freezes instead of showing gdb> and waiting for a command.

I'd say the stack is messed up or something, however like I said, this only happens when both threads are running at high speeds. The program ran fine for 20 minutes straight if I kept the playback thread running slowly (10 ticks per second). I'm confused. I hope this is some noob mistake because I have no idea how to debug this. I can't post any actual code either because it's a rather large program.

0

#### Share this post

##### Share on other sites

Are those member functions or free functions?

If multiple threads are accessing common memory, you'll probably need some kind of proper synchronisation. There are lots of really weird behaviour that can occur when multiple threads read and write data at the same time. For example, it is not guaranteed that all threads will see the same value of a variable if it has changed in another thread, they might see the old value indefinitely, they might see the new value after a non-deterministic amount of time, or they might see a partial change! Using proper threading primitives, such as a mutex, in the correct way can fix this.

Dev-C++ is rather old and unmaintained, and the compiler toolchain it ships with is very out of date. I'd highly suggest you use more modern IDE, two popular choices are Microsoft's Visual C++ (you can get free versions) and Code::Blocks. Both will ship with up to date compilers.

That aside, I'd recommend attempting to reduce the program as much as possible to the essential case which continues to demonstrate the problem. Unfortunately, threading bugs can be very timing dependent, which complicates this approach - just because removing a certain portion of code changes the result, does not mean that code is responsible for the problem.

0

#### Share this post

##### Share on other sites

Are those member functions or free functions?

If multiple threads are accessing common memory, you'll probably need some kind of proper synchronisation. There are lots of really weird behaviour that can occur when multiple threads read and write data at the same time. For example, it is not guaranteed that all threads will see the same value of a variable if it has changed in another thread, they might see the old value indefinitely, they might see the new value after a non-deterministic amount of time, or they might see a partial change! Using proper threading primitives, such as a mutex, in the correct way can fix this.

Dev-C++ is rather old and unmaintained, and the compiler toolchain it ships with is very out of date. I'd highly suggest you use more modern IDE, two popular choices are Microsoft's Visual C++ (you can get free versions) and Code::Blocks. Both will ship with up to date compilers.

That aside, I'd recommend attempting to reduce the program as much as possible to the essential case which continues to demonstrate the problem. Unfortunately, threading bugs can be very timing dependent, which complicates this approach - just because removing a certain portion of code changes the result, does not mean that code is responsible for the problem.

The funny part is it behaves in the exact same way with and without mutexes. Speaking of which, I just posted a new thread asking a very basic question about mutexes, before I saw your reply. I really need to turn on notifications. Would you mind taking a look? If my train of thought isn't total rubbish then that could be my problem.  http://www.gamedev.net/topic/652395-are-mutexes-really-fool-proof/

If that doesn't pan out as a possibility then my I'll have to somehow strip the program down as you've said. Not a pretty thought, but if it has to be done then so be it. I thought about using sockets but my data is too big for me to afford keeping multiple copies in memory like that. About 40MB per object, needing to keep at least 21 loaded and uncompressed at any given point. That'd be a minimum of 840MB per playback thread. nope.jpg

Thank you!

PS: I'm using this version of Dev-C++. I don't know how he did it but it's much better than the unmaintained original Bloodshed version. No more random crashes and no more immortal tooltips, yet it does retain the magic of Dev-C++.

Edited by Nüb?ek Pænus
0

## 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
Followers 0

• 11
• 19
• 14
• 23
• 11