从两个不同的线程调用一个函数,并将关键部分放入被调用的函数中 [英] Calling a function from two different threads and putting critical section inside the called function

查看:150
本文介绍了从两个不同的线程调用一个函数,并将关键部分放入被调用的函数中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数Writedata,它将打开文件并将数据写入文件。从不同的线程调用此函数,这些线程存在于不同的项目中。我想在函数内部使用criticalsection,这样两个线程都不会同时访问文件。我不知道在哪里初始化关键部分。你可以帮我写一下如何写关键部分(我的意思是在哪里放置InitializeCriticalSection,EnterCriticalSection代码)。



下面是示例代码



project1:

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:

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

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





project2:





project2:

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





project3:





project3:

void Thread2(void * arg)
{
       ....
       ....
       Writedata("text1");
}

推荐答案

我认为:

1.所有项目都是作为单个进程。

2.在project2和project3之间没有执行其他同步(即,在调用WriteData()时它们不保存任何其他同步对象。)



如果任何一个假设是假的,你可能需要一个不同的解决方案来解决你的问题。



Enter / LeaveCriticalSection API应放在可能的最小代码块。在这种情况下,这将在project1中的WriteData()函数内部。



放置Enter / LeaveCriticalSection调用指示应该调用Initialize / TerminateCriticalSection API的位置。在这种情况下,它们应该放在project1的初始化代码中。如果project1是一个DLL,应该可以将它放在启动/终止进程期间调用的DllMain()函数中。
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.


这篇关于从两个不同的线程调用一个函数,并将关键部分放入被调用的函数中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆