windows 和linux 同步api對比


 

初始化臨界區

(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)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM