views:

142

answers:

3

I want to run three threads (i) one should append strings into a file.(ii) The other thread should remove special characters from the written stream.(iii)The third thread should sort the words in ascending order.How could i do it in a thread safe(synchronized) manner ?

I mean

Thread 1

sample.txt

Apple
Ma#22ngo
G@ra&&pes

Thread 2 (after removing special characters sample.txt)

Apple
Mango
Grapes

Thread 3 (sample.txt)

Apple
Grapes
Mango
+6  A: 

Why do you want to do this using several threads? Perhaps your example has been oversimplified, but if you can avoid threading then do so - and it would appear that this problem doesn't need it.

Do you have lots of files, or one really large file, or something else? Why can't you simply perform the three actions one after another?

UPDATE

I felt I should at least try and help you solve the underlying problem you're facing. I think you need to consider the task you're looking at as a pipeline. You start with strings, you remove special characters (clean up), you write them to file. When you've finally written all the strings you need to sort them.

Everything up to the sorting stage can, and should, be done by a single thread. Read string, clean it, write it to file, move to next string. The final task of sorting can't easily happen until all the strings are written cleanly to the file.

If you have many files to write and sort then each of these can be dealt with by a seperate thread, but I would avoid involving multiple threads in the processing of any one given file.

Martin Peck
+2  A: 

I would perform operation 1 and 2 in the same thread by removing special characters before writing to the file. Operation 3 cannot be run in parallel with others because while the file is being written you cannot read it and sort. So basically these operations are sequential and it makes no sense to put them into separate threads.

Darin Dimitrov
+1  A: 

You should implement a ThredSafe Queue (or use the one that comes with Parallels extensions).

Threads have the problem of sharing information so, even if theoretically your solution would be seen as a perfect parallel scenario, the reality is you can't just let the threads access freely to the shared data, because when you do, bad things happen.

Instead you can use a synchronization mechanism, in this case a ConcurrentQueue. That way you'll have this:

ConcurrentQueue<string> queueStrings;
ConcurrentQueue<string> queueFile;

Thread1 inserts strings into the queueStrings queue.

Thread2 reads strings from the queueString, process them, and then inserts them into the queueFile queue.

Finally, Thread3 reads the processed strings from queueFile and write them into the file.

Jorge Córdoba
you mean C# 4.0 ..?
I am working in C# 3.0
Yeah, you can get it either with the Parallels extensions CTP or the c# 4.0 ... or implement it yourself
Jorge Córdoba