1

I have a multi-threaded(3 threads) C++ application to create three files in a single location. The application gets a start and stop command as input(say a user input at runtime). For each start-stop pair, all three threads should create files in a same folder.

I am using a single shell script to create file paths for each file generated by each of the three threads. There is a shell script which is getting called from within each thread. The shell script reads a number maintained in a common file called "count" and creates a string(filepath) using this count, with the count number appended to the directory to signify a new set. The number inside the "count" file should be updated only by the first thread that receives the update flag or "start_flag" from user input

The shell script is run inside the C++ file as follows:

Global variable to capture the start file update:

bool start_flag = false;

Inside each of the threads, there is something like:

if(true == start_flag) /*one of the threads that first receives the start signal*/    
    system("./folderpath.sh"); /*This will create a new string by incrementing count and update the file path in a file which will be later read*/    
else
    system("./folderpath.sh"); /*This will create a string using teh same count previously updated by another thread */

Inside the shell script, I am creating a text string and writing it into a file called Filepath.txt. I read this file to finally fopen a file in the generated path

I want to ensure that correct strings are updated in each of the Filepath.txt and read the content updated in the Filepath.txt by each of the threads without any issues

I observe that I am not getting what is expected.

How do I fix this?

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
Sushant
  • 151
  • 1
  • 7

1 Answers1

1

First, your code seems like it doesn't change the arguments to the folderpath.sh script, depending on the value of start_flag. Without passing some kind of information to the shell script, it's going to be hard to get it to do something different for one thread than for the others.

Secondly, you will need to use some sort of mutual exclusion to ensure that only one thread sees the "start_flag" set to "true" at a time. Since you mentioned shell scripts, it's probably a safe guess that you're on a POSIX system, which means you can use the pthreads API.

Since you're kicking off the the process in response to an input of some sort, it might make sense to have a condition variable that each of the threads waits on, then run the shell script once on the main thread with the appropriate flag to have it create a new path. Once that's done, broadcast the condition variable to have it start all of the other threads to use the new path.

Mark Bessey
  • 19,598
  • 4
  • 47
  • 69