初始化临界区
(win)
InitializeCriticalSection(RTL_CRITICAL_SECTION &rtl_critial_section)
(linux)
pthread_mutexattr_init(&(mutex)->attr);
pthread_mutexattr_settype(&(mutex)->attr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&(mutex)->mtx, &(mutex)->attr);
删除临界区
(win)
DeleteCriticalSection(RTL_CRITICAL_SECTION &)
(linux)
pthread_mutex_destroy(pthread_mutex_t &mutex)
进入临界区
(win)
EnterCriticalSection(RTL_CRITICAL_SECTION &rtl_critical_section)
(linux)
pthread_mutex_lock(pthread_mutex_t &mutex)
尝试进入临界区
(win)
TryEnterCriticalSection(RTL_CRITICAL_SECTION &rtl_critical_section )
(linux)
pthread_mutex_trylock(pthread_mutex_t &mutex)
离开临界区
(win)
LeaveCriticalSection(RTL_CRITICAL_SECTION &rtl_critical_section )
(linux)
pthread_mutex_unlock(pthread_mutex_t &mutex)
把目标操作数(第1参数所指向的内存中的数)与一个值(第3参数)比较,如果相等,则用另一个值(第2参数)与目标操作数(第1参数所指向的内存中的数)交换;InterlockedExchange是不比较直接交换。整个操作过程是锁定内存的,其它处理器不会同时访问内存,从而实现多处理器环境下的线程互斥
(win)
InterlockedCompareExchange(Destination, newvalue, oper)
(linux)
__sync_val_compare_and_swap(Destination, oper, newvalue)
v的值原子添加P的大小
(win)
InterlockedExchangeAdd(V, P)
(linux)
__sync_fetch_and_add(V, P)
原子增加一
(win)
InterlockedIncrement(T)
(linux)
__sync_fetch_and_add(T, 1)
原子减少一
(win)
InterlockedDecrement(T)
(linux)
__sync_fetch_and_sub(T, 1)
获取当前线程id
(win)
GetCurrentThreadId()
(linux)
syscall(SYS_gettid)
如果指定一个非零值,函数处于等待状态直到hHandle 标记的对象被触发,或者时间到了。如果dwMilliseconds 为0,对象没有被触发信号,函数不会进入一个等待状态,它总是立即返回。如果dwMilliseconds 为INFINITE,对象被触发信号后,函数才会返回。对应的linux实现使用条件变量
(win)
WaitForSingleObject(event,INFINITE)
(linux)
pthread_mutex_lock( &m_tx );
pthread_cond_wait( &event, &m_tx );
pthread_mutex_unlock( &m_tx );
退出线程(退出参数0)
(win)
ExitThread(0)
(linux)
pthread_exit(0)
设置线程优先级,pthread_setschedparam在多线程开发中经常被使用的,它主要用于设置线程的调用策略和优先级
(win)
SetThreadPriority (handle,nPrioroty)
(linux)
sched_param sp = {nPriority};
if(0 == pthread_setschedparam(m_pid, SCHED_RR, &sp))
{
return true;
}
return false;
获取优先级
(win)
GetThreadPriority( Handle m_hThread )
(linux)
int policy;
sched_param sp;
pthread_getschedparam(m_pid, &policy, &sp))
sp.sched_priority;
初始化互斥量
(linux)
pthread_mutex_init(pthread_mutex_t &mutex),0)
初始化条件变量
pthread_cond_init(&cond,0)
删除互斥量
pthread_mutex_destroy(pthread_mutex_t &mutex))
删除条件变量
(linux)
pthread_cond_destroy(pthread_cond_t &cond)
向条件变量发起信号
(linux)
pthread_cond_signal(pthread_cond_t &cond)
挂起等待结束(无限等待) true在阻塞期间允许进入警告状态(windows才有)
(win)
WaitForSingleObject Ex(handle, INFINITE,true)
(linux)
pthread_join (pthread_t thid, void ** ret_val) 常用pthread_join(pid,0)