读书人

多线程同步 急解决方案

发布时间: 2012-03-03 15:33:03 作者: rapoo

多线程同步 急
现在有三个线程, A 线程负责与下位机通讯, B线程负责数据分析显示 C 线程负责存储数据


很显然B 和 C 线程 都得依赖于A 线程 取的数据.

也就是说 A 线程 先取得数据 然后 把数据给B 和 C 线程,B 和 C 线程处理完了后 A 线程又 开始取数据 就这样循环下去.


那么如何实现他们之间的同步呢??

看了线程同步的资料,能用事件和临界区同步,但具体如何实现呢?
ps:比较穷,只能给30分,望高手们帮忙

[解决办法]
CCriticalSection Section;

//A线程
Section.Lock();
for ( int m = 0; m < 10; m++ )
{
//写数据 共享数据区
}
Section.Unlock();

//B,C线呈处理方式
Section.Lock();
//读写数据 共享数据区
Section.Unlock();



[解决办法]
找个用事件的例子来了

HANDLE g_hevt;

static void thread_a( void* para )
{

/* do something */

SetEvent( g_hevt );

return;
}

static void thread_b( void* para )
{
WaitForSingleObject( g_hevt, INFINITE );

/* do something */

return;
}

static void thread_c( void* para )
{
WaitForSingleObject( g_hevt, INFINITE );

/* do something */

return;
}

int main( int argc, char *argv[] )
{
g_hevt = CreateEvent( NULL, TRUE, FALSE, NULL );

_beginthread( thread_a, 0, NULL );
_beginthread( thread_b, 0, NULL );
_beginthread( thread_c, 0, NULL );

/* ... */

system( "PAUSE ");
return 0;
}
[解决办法]
HANDLE g_hevt[3];

#define EVT_A 0
#define EVT_B 1
#define EVT_C 2

static void thread_a( void* para )
{

WaitForSingleObject( g_hevt[EVT_A], INFINITE );

/* do something */

SetEvent( g_hevt[EVT_B] );

return;
}

static void thread_b( void* para )
{
WaitForSingleObject( g_hevt[EVT_B], INFINITE );

/* do something */

SetEvent( g_hevt[EVT_C] );

return;
}

static void thread_b( void* para )
{
WaitForSingleObject( g_hevt[EVT_C], INFINITE );

/* do something */

SetEvent( g_hevt[EVT_A] );

return;
}

int main( int argc, char *argv[] )
{
g_hevt[EVT_A] = CreateEvent( NULL, TRUE, FALSE, NULL );
g_hevt[EVT_B] = CreateEvent( NULL, TRUE, FALSE, NULL );
g_hevt[EVT_C] = CreateEvent( NULL, TRUE, FALSE, NULL );

_beginthread( thread_a, 0, NULL );
_beginthread( thread_b, 0, NULL );
_beginthread( thread_c, 0, NULL );

SetEvent( g_hevt[EVT_A] )

/* ... */

system( "PAUSE ");
return 0;
}
[解决办法]
用这个试试
class MtkMutex
{
friend class MtkGuard;
private:
CRITICAL_SECTION cs_;

public:

inline MtkMutex(void)
{
::InitializeCriticalSection(&cs_);
}

inline ~MtkMutex(void)


{
::DeleteCriticalSection(&cs_);
}

private:
//锁定函数
inline void Lock()
{
::EnterCriticalSection(&cs_);
}
//解锁函数
inline void UnLock()
{
::LeaveCriticalSection(&cs_);
}

};

class MtkGuard
{
private:
intlockCount_;
MtkMutex*pMutexObject_;
public:
MtkGuard(MtkMutex* pMutex, bool bAutoLock = true)
:pMutexObject_(NULL)
,lockCount_(0)
{
pMutexObject_ = pMutex;
if(bAutoLock)
Lock();
}
~MtkGuard()
{
while (lockCount_ > 0)
UnLock();
}
public:
void Lock()
{
if(pMutexObject_)
{
pMutexObject_-> Lock();
lockCount_ ++;
}
}
void UnLock()
{
if(pMutexObject_)
{
pMutexObject_-> UnLock();
lockCount_ --;
}
}
};

MtkMutex mutex_;

需要同步的地方:
MtkGuard guard(&mutex_);
lock在guard的构造函数里去做
unlock在析构里去搞
函数任何地方都可以随意返回,不用担心unlock

读书人网 >VC/MFC

热点推荐