全部我的爱 电视剧:多线程问题

来源:百度文库 编辑:中科新闻网 时间:2024/04/30 00:49:40
什么是多线程
有什么作用
最好用通俗的比喻
谢谢

006-04-27 20:57:40 评论 ┆ 举报

最佳答案此答案由提问者自己选择,并不代表百度知道知识人的观点

回答:dukejoe
学弟
5月4日 11:59 class CThreadParam
{
private:
int m_iCount ;
BOOL m_bRun ;
CRITICAL_SECTION m_csCriticalSection ;
CMainFrame * m_pFrame ;

public:
CThreadParam() ;
virtual ~CThreadParam() ;

int StepIt() ;
BOOL IsRun() ;
int Start(CMainFrame *pFrame) ;
int Finished () ;
private:
int Enter() ;
int Leave() ;
};
// CMainFrame 消息处理程序

void CMainFrame::OnThreadBegin()
{
if ( !m_tpGather.IsRun() )
{
m_tpGather.Start(this) ;
}
AfxBeginThread(GatherThread, &m_tpGather) ;
}

void CMainFrame::OnThreadEnd()
{
m_tpGather.Finished() ;
}

CThreadParam::CThreadParam()
{
InitializeCriticalSection(&m_csCriticalSection) ;
m_bRun = FALSE ;
m_iCount = 0 ;
}

CThreadParam::~CThreadParam()
{
DeleteCriticalSection(&m_csCriticalSection) ;
}

int CThreadParam::StepIt()
{
int iPrevCount = m_iCount ;
Enter() ;
m_iCount++ ;
Leave() ;

// 这部分代码也应该和前面的思路是一样的,由视图来提供方法进行更新,但这样做就太过复杂了
// 我这不是实际工程,所以在这里为了节省时间对于视图的算法不做演示了
((Ctest3View*)m_pFrame->GetActiveView())->m_iCount = iPrevCount ;
((Ctest3View*)m_pFrame->GetActiveView())->Invalidate() ;

return iPrevCount ;
}

int CThreadParam::Enter()
{
EnterCriticalSection(&m_csCriticalSection);
return 0 ;
}

int CThreadParam::Leave()
{
LeaveCriticalSection(&m_csCriticalSection);
return 0 ;
}

BOOL CThreadParam::IsRun()
{
return m_bRun ;
}

int CThreadParam::Start(CMainFrame *pFrame)
{
m_bRun = TRUE ;
m_iCount = 0 ;
m_pFrame = pFrame ;
return 0 ;
}

int CThreadParam::Finished()
{
m_bRun = FALSE ;
return 0 ;
}

UINT GatherThread( LPVOID pParam )
{
CThreadParam * tp = (CThreadParam *)pParam ;

while ( tp->IsRun() )
{
tp->StepIt() ;
::Sleep(2000) ;
}
return 0 ;
}
public:
int m_iCount;

这是我在天极网的VC论坛回贴的一个关于线程的问题
http://bbs.yesky.com/bbs.php?url=/viewthread2.php?tid=2584119&pid=&page=

里面正好也是一个最基本的线程控制代码。其中程序是基于SDI的,但给出的代码都是和线程有关的。其中主要是一些同步和互斥的东西。第一位朋友给如的代码并没有在printf时进行互斥,所以这样的多线程一定会出现问题,上面给出的代码是最基本的进出临界区的框架,写得不好,但大致就是那个意思。如果没有这部分代码而像第一位朋友那样写,多线程没有同步,就必然要运行中会出现问题。另外也可能是第一位朋友的疏忽,他在进行线程前malloc,但出去后没有free这也会导致明显的内存泄露。这一点儿也稍微有点不妥。

揪错 ┆ 评论 ┆ 举报