#Mutex or not to mutex?

12 messages · Page 1 of 1 (latest)

quiet cobalt
#

I have a chunk system(pretty much like minecraft). And each chunk ahve to save its state:

  1. Every couple of minutes
  2. When its being despawned

Someone mentioned using mutex on the chunk's data(e.g. blocks placed), but I'm not fully convinced, I heard that mutexes can slow program down quite a lot, and in this case, chunk's data will be constantly read and written(for other stuff than just saving and loading).

Should I keep with mutexes, or should I rather make something lock-free, where the other thread will just read the data, copy it and make save out of the copy?

wheat thorn
# quiet cobalt I have a chunk system(pretty much like minecraft). And each chunk ahve to save i...

You don't need mutexes for this. Assuming you want to let the game schedule continue while also saving the data, what you want is just to copy the data, and then save it to disk (On another thread/using an async task). Using a mutex would not help, as sure, you could read the data directly, and then write it to disk, without the in-between copy, you would end up locking up the rest of the systems relying on being able to access the chunk data. Also you don't need a mutex to read/write to chunks, since bevy already makes sure that the several &T or one &mut T, rule is upheld (Also for resources)

quiet cobalt
wheat thorn
slim swift
# quiet cobalt I wonder if there is a way to copy a data on the other thread. What if there is ...

Threads [on most architectures] start sharing cache at l3, you don't usually have to worry about the copying data between them issue until you exceed the capacity of l3 cache, having said that modern CPU prefetch is very good, if your data is contiguous and there's no pointer chasing you can achieve L2 cache read speeds at system RAM. if you want to seriously profile whether this will be an issue for your application dive into your specific CPUs cache write back policy and do some benching.

quiet cobalt
slim swift
#

Pretty much you have no control [practically speaking ] about what your CPU is doing down there so it doesn't really matter

#

There are assembly instructions for 'put this in l2' but I wouldn't recommend using them

#

If your data is <32MB the point is mute anyway because you'd be 'limited' to the speed that l3 is pulled into L2.. into l1. And so on

#

There may be other stuff in l3 from other processes etc and so on

#

The solution is benchmarking

#

And profiling