如何在共享库中的一种方法上同步线程 [英] How to synchronize threads on one method in shared object

查看:73
本文介绍了如何在共享库中的一种方法上同步线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法同步访问校准对象.
我有两个摄像头对象,它们获得单帧,然后尝试在校准对象中都访问相同的方法.问题在于,看起来每个摄像机都在单独的线程上运行,并且它们试图同时访问校准中的方法,这会使我的程序崩溃.
我尝试使用EnterCriticalSection,但没有任何乐趣.如果在下面的代码中它不起作用,并且在AddImage中它正在创建访问冲突.
在一种方法上同步线程的最简单方法是什么?

I got problem with synchronizing access to calibration object.
I have two camera objects that get single frame and then try to both access same method in calibration object. Problem is that it looks like each camera runs on separate thread and they try to access method in calibration at the same time which crashes my program.
I tried using EnterCriticalSection but with no joy. If it was in the code below it was not working and if it was in AddImage it was creating access violation.
What is easiest way to synchronize threads on one method?

HRESULT STDMETHODCALLTYPE Camera::BufferCB( double SampleTime, BYTE *pBuffer, long BufferLen )
{
	  
   if(go ==1)
   {
        
      IplImage* tempImage;
      tempImage = calibration->CreateGrayImage(pBuffer, cameraNumber);
      calibration->AddImage(tempImage,cameraNumber);
        	
    }
    go=0;
    
    return 0;
}



[修改:将代码标记更改为前置标记]



[Modified: changed code tags to pre tags]

推荐答案

希望这些文章对您有所帮助:

《多线程实用指南-第1部分》 [多线程实用指南-第2部分 [
Hope these articles would help you:

The Practical Guide to Multithreading - Part 1[^]
The Practical Guide to Multithreading - Part 2[^]


看看CMutex类.
您将在CP的文章中找到一些示例,搜索CMutex.
Have a look at the CMutex class.
You''ll find some examples in the Articles on CP, do a search for CMutex.


好吧,我现在知道该怎么做.

在Calibration :: AddImage的目标方法中,我需要添加

Ok I know now how to do it.

In target method here in Calibration::AddImage I need to add

Calibration::AddImage(Iplimage*, int rightLeft)
{
HANDLE g_Mutex;
DWORD dwWaitResult;

// Create a mutex with initial owner.

g_Mutex = CreateMutex( NULL, TRUE, "MutexToProtectCalibration");
 
// Wait for ownership

dwWaitResult = WaitForSingleObject( g_Mutex, 5000L);

// Check takes ownership

//Here should be all my method code

// Release Mutex

ReleaseMutex(g_Mutex))

}



这意味着任何同步都需要在目标代码中完成.基本上,这就是我在文章中所缺少的解释.



this means that any synchronization need to be done in target code. That was basically explanation I was missing from articles.


这篇关于如何在共享库中的一种方法上同步线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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