Search code examples
c++multithreadingvisual-studio-2005

c++ Handling multiple threads in a main thread


I am a bit new to multi threading, so forgive me if these questions are too trivial.

My application needs to create multiple threads in a thread and perform actions from each thread.

For example, I have a set of files to read, say 50 and I create a thread to read these files using CreateThread() function.

Now this main thread creates 4 threads to access the file. 1st thread is given file 1, second file 2 and so on.

After 1st thread completed reading file 1 and gives main thread the required data, main thread needs to invoke it with file 5 and obtain data from it. Similar goes for all other threads until all 50 files are read.

After that, each thread is destroyed and finally my main thread is destroyed.

The issue I am facing is:

1) How to stop a thread to exit after file reading?

2) How to invoke the thread again with other file name?

3) How would my child thread give information to main thread?

4) After a thread completes reading the file and returns the main thread a data, how main thread would know which thread has provided the data?

Thanks


Solution

  • This is a very common problem in multi-threaded programming. You can view this as a producer-consumer problem: the main thread "produces" tasks which are "consumed" by the worker threads (s. e.g. http://www.mario-konrad.ch/blog/programming/multithread/tutorial-06.html) . You might also want to read about "thread pools".

    I would highly recommend to read into boost's Synchronization (http://www.boost.org/doc/libs/1_50_0/doc/html/thread.html) and use boost's threading functionality as it is platform independent and good to use.

    To be more specific to your question: You should create a queue with operations to be done (usually it's the same queue for all worker threads. If you really want to ensure thread 1 is performing task 1, 5, 9 ... you might want to have one queue per worker thread). Access to this queue must be synchronized by a mutex, waiting threads can be notified by condition_variables when new data is added to the mutex.

    1.) don't exit the thread function but wait until a condition is fired and then restart using a while ([exit condition not true]) loop

    2.) see 1.

    3.) through any variable to which both have access and which is secured by a mutex (e.g. a result queue)

    4.) by adding this information as the result written to the result queue.

    Another advice: It's always hard to get multi-threading correct. So try to be as careful as possible and write tests to detect deadlocks and race conditions.