Click here to Skip to main content
15,069,581 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

void Writedata(szCmdData){
	ofstream outfile(file1);

		outfile << szCmdData; 


void Thread1(void * arg)


void Thread2(void * arg)
Updated 30-Dec-15 3:35am

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.
Sergey Alexandrovich Kryukov 30-Dec-15 11:58am
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