views:

236

answers:

2

In C:

If I have 3 threads, 2 threads that are appending strings to a global char string (char*), and 1 thread that is reading from that char string.

Let's say that the 2 threads are appending about 8 000 strings per second each and the 3rd thread is reading pretty often too. Is there any possibility that they will append at exactly the same time and overwrite each other's data or read at the same time and get an incomplete string?

+8  A: 

Yes, this will get corrupted pretty quickly

You should protect access to this string with a mutex or read/write locking mechanism.

I'm not sure what platform you're on but have a look at the pthreads library if you're on a *nix platform.

I don't develop for windows, so I can't point you at any threading capabilities (though I know there's plenty of good threading API in Win32

Edit

@OP have you considered the memory issues of appending 8000 strings (you don't state how large each string is) per second. You're going to run out of memory pretty quickly if you're never removing data from your global string. You might want to consider bounding the size of this string somehow, and also setting up some kind of system to remove data from your string (the reader thread would be the best place for this). If you're already doing that, then ignore the above.

Glen
As Tom notes, "it is pretty likely that this will" is most probably an understatementfor "it **will**", especially on a multi-core machine.
Jonathan Leffler
@Jonathan. You're right. I've updated my answer, thanks for pointing that out
Glen
Hi thank for your answers, the string size is maybe around 100 chars, and I empty the string after every read.I just ran some tests and yeah, like Tom wrote, it does overwrite aech other :(I'm on Linux.
@Timothy, as you're on linux then pthreads is the way to go for protecting access to this global.
Glen
+2  A: 

Is there any possibility that they will append exact on the same time and overwrite each others data or read on the same time and get an incomplete string?

When dealing with concurrent issues, you must always protect your data. You can never leave this kind of stuff to chance. Even if there's 0.1% chance of trouble, it will happen.

Tom
+1 for "it **will** happen".
Jonathan Leffler