Jump to content

  • Log In with Google      Sign In   
  • Create Account

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


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
8 replies to this topic

#1 Nübček Pænus   Members   -  Reputation: 153

Like
0Likes
Like

Posted 22 December 2013 - 04:50 PM

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();
}



Sponsor:

#2 rip-off   Moderators   -  Reputation: 8764

Like
1Likes
Like

Posted 22 December 2013 - 05:30 PM

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.



#3 Nübček Pænus   Members   -  Reputation: 153

Like
0Likes
Like

Posted 22 December 2013 - 11:09 PM

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, 22 December 2013 - 11:10 PM.


#4 C0lumbo   Crossbones+   -  Reputation: 2501

Like
0Likes
Like

Posted 23 December 2013 - 01:50 AM

 

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.



#5 Nübček Pænus   Members   -  Reputation: 153

Like
0Likes
Like

Posted 24 December 2013 - 12:38 AM

 

 

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!



#6 rip-off   Moderators   -  Reputation: 8764

Like
0Likes
Like

Posted 24 December 2013 - 03:52 PM


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.



#7 Nübček Pænus   Members   -  Reputation: 153

Like
0Likes
Like

Posted 12 January 2014 - 01:40 PM

 


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.



#8 rip-off   Moderators   -  Reputation: 8764

Like
0Likes
Like

Posted 16 January 2014 - 06:04 PM

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.



#9 Nübček Pænus   Members   -  Reputation: 153

Like
0Likes
Like

Posted 19 January 2014 - 01:44 AM

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++. biggrin.png biggrin.png


Edited by Nübček Pænus, 19 January 2014 - 01:46 AM.





Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS