Thread safe char string in C

In C:

If I have 3 streams, 2 streams that attach strings to a global char (char *) string, and 1 stream that reads from that char string.

Let's say that 2 threads add about 8000 rows per second, and the third thread also reads quite often. Is there a chance that they will be added at exactly the same time and overwrite each other's data, or read at the same time and receive an incomplete string?

+2


source to share


2 answers


Yes, it will go bad quickly.

You must protect access to this row with a mutex or read / write locking mechanism.

I'm not sure which platform you are on, but take a look at the pthreads library if you are on a * nix platform.



I am not developing for Windows, so I cannot point you to any streaming capabilities (although I know there are many good streaming APIs in Win32

Edit

@OP looked at memory issues of adding 8000 lines (you didn't mention how big each line is) per second. You will soon run out of memory if you never delete data from your global string. You might want to limit the size of that string in some way, and also set up some system to remove data from your string (a reader stream would be best used for this). If you've already done this, then ignore the above.

+7


source


Is there a chance that they will be added at exactly the same time and overwrite each other's data, or read at the same time and get an incomplete string?



When dealing with concurrent problems, you should always protect your data. You can never leave such things to their fate. Even if there is a 0.1% chance of trouble, it will .

+2


source







All Articles