实现线程同步的几种方法

1. 利用互斥对象实现线程同步
互斥对象(mutex)属于内核对象,主要函数:

The CreateMutex function creates or opens a named or unnamed mutex object.

HANDLE CreateMutex(
LPSECURITY_ATTRIBUTES lpMutexAttributes,
  BOOL bInitialOwner,
  LPCTSTR lpName
);


The ReleaseMutex function releases ownership of the specified mutex object.

 

BOOL ReleaseMutex(
HANDLE hMutex
);

The WaitForSingleObject function returns when one of the following occurs:

 

  • The specified object is in the signaled state.
  • The time-out interval elapses.

To enter an alertable wait state, use the WaitForSingleObjectEx function. To wait for multiple objects, use the WaitForMultipleObjects.

 

DWORD WaitForSingleObject(
HANDLE hHandle,
DWORD dwMilliseconds
);
2. 利用事件对象实现线程同步
主要函数:

The CreateEvent function creates or opens a named or unnamed event object.

 

HANDLE CreateEvent(
LPSECURITY_ATTRIBUTES lpEventAttributes,
BOOL bManualReset,
BOOL bInitialState,
LPCTSTR lpName
);

The SetEvent function sets the specified event object to the signaled state.

 

BOOL SetEvent(
HANDLE hEvent
);
The ResetEvent function sets the specified event object to the nonsignaled state.

 

BOOL ResetEvent(
HANDLE hEvent
);
3. 关键代码
关键代码段, 也称为临界区,工作在用户方式下。它是指一个小代码段,在代码能够执行前,它必须独占对某些资源的访问权
 
主要函数:
The InitializeCriticalSection function initializes a critical section object.

 

void InitializeCriticalSection(
LPCRITICAL_SECTION lpCriticalSection
);

The EnterCriticalSection function waits for ownership of the specified critical section object. The function returns when the calling thread is granted ownership.

 

void EnterCriticalSection(
LPCRITICAL_SECTION lpCriticalSection
);
The LeaveCriticalSection function releases ownership of the specified critical section object.

 

void LeaveCriticalSection(
LPCRITICAL_SECTION lpCriticalSection
);
三种方法的区别在于:
互斥对象和事件都属于内核对象,利用内核对象进行线程同步时速度较慢,但利用这两种方法可以在多个进程的各个线程间进行同步
关键代码段工作方式下,同步速度较快, 但很容易产生死锁,因为在等待进入关键代码段时无法设定超时值
 






posted on 2007-04-20 11:18 ffan 阅读(1501) 评论(0)  编辑 收藏 引用 所属分类: C/C++/VC

只有注册用户登录后才能发表评论。
<2009年6月>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

导航

统计

常用链接

留言簿(12)

随笔分类

随笔档案

相册

搜索

最新评论

阅读排行榜

评论排行榜