Thread synchronization


0I am makin a program in c++ where i am loggin some values in .txt file.

I am using threading so that the main program is not affected

Now my problem is that i am gettin the required output in my log file but it does not comes in the right sequence when i call the loggin function multiple times.

For eg

writelog("123");

writelog("456");

writelog("789");

Output

123

789

456

but i want it to be in order.

When i execute my program multiple time i get this type of output only once or twice .plsss help me





I am using threading so that the main program is not affected

Affected in what way?
affected as in the logging thing is done in a separate thread
What advantage does that have?

It looks like you are spawning a new thread each call to writelog. Don't do that. If you want to use threads, have a separate thread running that writes outputs from a queue, and have the writelog function add to that queue.
thanks Peter87 i will surely look into that but before that plss help me solve my problem regarding thread synchronization

problem more specified

the user will call the function like

writelog("123");

writelog("456");

writelog("789");

now the values 123 would be read one by one and concatinated as a string and in the end the string would be passed as a argument to the createthread function.

hthread[1]=CreateThread(
NULL,
0,
MyThreadFunction, //function name where log is generated using fstream obj
dataarray1,//struct obj whose member is the string which is passes to the above function
0,
&dwthreadid[1]);

now after the values 123 have been read the next output should be 456 but sometimes the output comes out to be 45 or 678 and then 456

it just gets mixed



myfile<<"\n"<<*dataarray1->pstr; // this is where i access the struct
dataarray1->pstr="";//if i dont make this empty then the output is is like
123
123456
123456789
the previous string keeps on gettin appended

Topic archived. No new replies allowed.