Click here to Skip to main content
15,881,248 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
I have a function "Writedata" which will open the file and write the data to the file. This function is called from different thread which are present in different projects. I want to use criticalsection inside the function so that both threads will not access the file at the same time.I am not knowing where to initialize the critical sectio. Can you please help me for how to write the critical section (I mean where to put InitializeCriticalSection ,EnterCriticalSection code) .

Below is the sample code

project1:
C++
void Writedata(szCmdData){
	ofstream outfile(file1);

	if(outfile.is_open())
	{
		outfile << szCmdData; 
		outfile.close();
	}
}


project2:

C++
void Thread1(void * arg)
{
      ....
      .....
       Writedata("text1");
}


project3:

C++
void Thread2(void * arg)
{
       ....
       ....
       Writedata("text1");
}
Posted
Updated 30-Dec-15 3:35am
v2

1 solution

I assume that:
1. All projects are run as parts of a single process.
2. No other synchronization is performed between project2 and project3 (i.e. they don't hold any other synchronization objects when calling WriteData()).

If either assumption is false, you will probably need a different solution to your problem.

The Enter/LeaveCriticalSection APIs should be placed around the smallest block of code possible. In this case, this would be inside the WriteData() function in project1.

The placing of the Enter/LeaveCriticalSection calls dictates where the Initialize/TerminateCriticalSection APIs should be called. In this case, they should be placed in the initialization code for project1. If project1 is a DLL, it should be possible to place this in the DllMain() function that is called during startup/termination of the process.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 30-Dec-15 11:58am    
5ed.
—SA
krish0969 30-Dec-15 23:07pm    
Thanks Daniel :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900