天天看點

多線程程式設計相關技術

建立線程

1、Linux線程的建立

pthread_create函數

2、Windows線程的建立

CreateThread函數

3、windows CRT提供的線程建立函數

_beginthreadex函數,其聲明位于process.h頭檔案中

4、C++11提供線程的建立

C++11新标準引入std::thread(頭檔案)

擷取線程ID

1、在Linux系統中有三種方法可以擷取1個線程的ID:

方法一:調用pthread_create函數

#include <pthread.h>

pthread tid;

pthread_create(&tid, NULL, thread_proc, NULL);

方法二:調用pthread_self函數

#include <pthread.h>

pthread tid = pthread_self();

方法三:通過系統調用擷取線程ID

#include <sys/syscall.h>

#include <unistd.h>

int tid = syscall(SYS_gettid);

2、在windows平台上可以調用GetCurrentThreadID函數擷取

3、C++11擷取目前線程ID的方法

可以使用std::this_thread類的get_id擷取目前線程ID

等待線程結束

1、在Linux下等待線程結束

pthread_join函數

2、在windows下等待線程結束

WaitForSingleObject用于等待1個線程結束

WaitForMultipleObjects可以同時等待多個線程結束

3、C++11提供的等待線程結果的函數

std::thread的join方法

if (t.joinable())

t.join();

Linux線程同步對象

1、Linux互斥體

#include <pthread.h>

pthread_mutex_t mymutex;

pthread_mutex_init(&mymutex, NULL);

pthread_mutex_lock(&mymutex);

pthread_mutex_destroy(&mymutex);

2、Linux信号量

#include <semaphore.h>

int sem_init(sem_t* sem, int pshared, unsigned int value);

int sem_destroy(sem_t* sem);

int sem_post(sem_t* sem);

int sem_wait(sem_t* sem);

int sem_trywait(sem_t* sem);

3、Linux條件變量

int pthread_cond_init(pthread_cond_t* cond, const pthread_condattr_t* attr);

int pthread_cond_destroy(pthread_cond_t* cond);

4、Linux讀寫鎖

#include <pthread.h>

int pthread_rwlock_init(pthread_rwlock_t* rwlock, const pthread_rwlockattr_t* attr);

int pthread_rwlock_destroy(pthread_rwlock_t* rwlock);

Windows線程同步對象

1、WaitForSingleObject與WaitForMultipleObjects函數

WaitForSingleObject隻能等待單個對象

DWORD WaitForSingleObject(HANDLE hHandle, DWORD dwMilliseconds);

WaitForMultipleObjects同時等待多個對象

DWORD WaitForMultipleObjects(DWORD nCount, const HANDLE *lpHandles, BOOL bWaitAll, DWORD dwMilliseconds);

2、windows臨界區對象

InitializeCriticalSection

DeleteCriticalSection

TryEnterCriticalSection

EnterCriticalSection

LeaveCriticalSection

3、Windows Event對象

CreateEvent ---- 建立Event對象

SetEvent ---- 将對象變成受信狀态

ResetEvent ---- 将對象變成無信号狀态

可以同時喚醒多個線程,卻不能精确地控制同時喚醒指定數量的線程。

4、Windows Mutex對象

CreateMutex

5、windows Semaphore對象

CreateSemaphore

可以精确地控制同時喚醒指定數量的線程

6、windows讀寫鎖

Slim Reader/Writer(SRW) Locks

7、windows條件變量

CONDITION_VARIABLE

C++11/14/17線程同步對象

1、std::mutex系列

lock加鎖

trylock嘗試加鎖

unlock解鎖

2、std::shared_mutex

底層實作是作業系統提供的讀寫鎖

3、std::condition_variable

條件變量

多線程使用鎖經驗總結

1、減少鎖的使用次數

2、明确鎖的範圍

3、減少鎖的使用粒度

盡量減少鎖作用的臨界區代碼範圍

4、避免死鎖

5、避免活鎖

線程池、隊列、纖程和協程

1、線程池

一組線程

2、隊列

3、纖程

既能建立線程執行任務,又沒有建立線程消耗那麼大

4、協程

應用層模拟的線程

繼續閱讀