iOS多線程之pthread

pthread是POSIX Threads的縮寫,POSIX是Protable Operating System Interface的縮寫,即可移植操作系統(tǒng)接口。pthread的本質(zhì)是可移植操作系統(tǒng)接口標準中有關(guān)多線程部分的實現(xiàn),是一套由C語言編寫的多線程接口,可用于Linux、Windows、iOS等操作系統(tǒng)。
使用pthread進行iOS多線程開發(fā),相比其他方式,較為復雜,因此在實際開發(fā)中較少使用pthread進行多線程開發(fā)。

一、pthread的簡單使用

使用pthread來創(chuàng)建一個新的線程并執(zhí)行任務(wù),示例如下:

#import "ViewController.h"
#import "pthread.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    NSLog(@"%p", pthread_self());
    pthread_t thread;
    pthread_create(&thread, NULL, task, @"test");
    pthread_detach(thread);
}

void *task(void *param) {
    NSLog(@"%p", pthread_self());
    NSLog(@"當前線程:%@,參數(shù):%@", [NSThread currentThread], param);
    return NULL;
}

運行代碼,控制臺輸出如下:

2022-01-02 14:47:58.441269+0800 MyProject[98533:2025812] 0x111c47e00
2022-01-02 14:47:58.441454+0800 MyProject[98533:2026535] 0x7000062ff000
2022-01-02 14:47:58.441644+0800 MyProject[98533:2026535] 當前線程:<NSThread: 0x6000035882c0>{number = 7, name = (null)},參數(shù):test

可見task函數(shù)執(zhí)行的任務(wù)并不是在主線程中執(zhí)行的,而是創(chuàng)建了一個新的線程執(zhí)行任務(wù)。
pthread_self()用來獲取當前線程,返回一個pthread_t類型的結(jié)構(gòu)體。

  • pthread_create(pthread_t _Nullable *restrict _Nonnull, const pthread_attr_t *restrict _Nullable, void * _Nullable (* _Nonnull)(void * _Nullable), void *restrict _Nullable)
    該函數(shù)用來創(chuàng)建一個新的pthread_t線程結(jié)構(gòu)體。
    參數(shù)1為pthread_t類型的地址;
    參數(shù)2位線程屬性配置參數(shù),用來對線程的狀態(tài)和行為進行設(shè)置;
    參數(shù)3位函數(shù)指針,用來指定線程要執(zhí)行的任務(wù);
    參數(shù)4為任務(wù)函數(shù)中需要傳遞的參數(shù),可以是任意類型。
  • pthread_detach(pthread_t _Nonnull)
    pthread線程被創(chuàng)建后立即開始執(zhí)行,執(zhí)行完成后不會默認釋放資源。該函數(shù)實際上是用來設(shè)置線程detach屬性的,即把線程設(shè)置為分離線程,當線程中的任務(wù)執(zhí)行結(jié)束后就自動釋放資源。
二、pthread線程配置屬性pthread_attr_t

pthread_create函數(shù)的第2個參數(shù)用來配置線程的屬性。線程屬性配置使用pthread_attr_t結(jié)構(gòu)體描述,使用之前,需要進行結(jié)構(gòu)體的初始化,示例如下:

pthread_attr_t attr;
pthread_attr_init(&attr);

【注意】
在使用pthread相關(guān)的接口時,要手動地進行內(nèi)存管理,因此創(chuàng)建的數(shù)據(jù)在使用完成后要進行銷毀,例如:

pthread_attr_destroy(&attr);

pthread_detach函數(shù)用來設(shè)置線程的分離狀態(tài),其中也可以通過屬性對其進行設(shè)置:

// 設(shè)置線程分離狀態(tài)屬性
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
int state;
// 獲取線程分離狀態(tài)屬性
pthread_attr_getdetachstate(&attr, state);

其中,PTHREAD_CREATE_DETACHED表示設(shè)置為分離線程,與之相對的還有一個設(shè)置為非分離線程的宏定義,具體如下:

#define PTHREAD_CREATE_JOINABLE      1
#define PTHREAD_CREATE_DETACHED      2

通過線程的guardsize屬性可以設(shè)置線程境界緩沖區(qū)的大小。這個數(shù)值決定線程棧末尾避免棧溢出的擴展內(nèi)存大小。示例如下:

// 設(shè)置緩沖區(qū)大小
pthread_attr_setguardsize(&attr, 128);
size_t guardSize;
// 獲取緩沖區(qū)大小
pthread_attr_getguardsize(&attr, &guardSize);

inheritsched屬性設(shè)置線程的繼承性。示例如下:

pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED);
int inheritsched;
pthread_attr_getinheritsched(&attr, &inheritsched);

與繼承性相關(guān)的宏定義如下:

/*
 * Thread attributes
 */
// 新的線程繼承創(chuàng)建線程的策略和參數(shù)
#define PTHREAD_CREATE_JOINABLE      1
// 新的線程繼承策略和參數(shù)來自于策略配置參數(shù)的設(shè)置
#define PTHREAD_CREATE_DETACHED      2

schedparam用來設(shè)置線程的調(diào)度參數(shù),其實質(zhì)是設(shè)置線程的優(yōu)先級,示例如下:

struct sched_param param = {1};
pthread_attr_setschedparam(&attr, &param);
struct sched_param p;
pthread_attr_getschedparam(&attr, &p);

schedpolicy設(shè)置線程的調(diào)度策略,示例如下:

pthread_attr_setschedpolicy(&attr, SCHED_FIFO);
int policy;
pthread_attr_getschedpolicy(&attr, &policy);

可設(shè)置的策略定義如下:

/*
 * POSIX scheduling policies
 */
#define SCHED_OTHER                1 // 其他
#define SCHED_FIFO                 4 // 先進先出
#define SCHED_RR                   2 // 輪轉(zhuǎn)

scope屬性設(shè)置線程的作用域,示例如下:

pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
int scope;
pthread_attr_getscope(&attr, &scope);

scope屬性控制線程的資源競爭方式,宏定義如下:

/* We only support PTHREAD_SCOPE_SYSTEM */
#define PTHREAD_SCOPE_SYSTEM         1
#define PTHREAD_SCOPE_PROCESS        2

從官方注釋可見,目前僅支持PTHREAD_SCOPE_SYSTEM

3、pthread常用函數(shù)
  • pthread_equal(pthread_t _Nullable, pthread_t _Nullable)
    比較兩個pthread_t線程是否相同,返回0表示不同,1表示相同。
  • pthread_exit(void * _Nullable)
    提前終止線程的執(zhí)行。
  • pthread_join(pthread_t _Nonnull, void * _Nullable * _Nullable)
    當線程設(shè)置為非分離線程(即PTHREAD_CREATE_JOINABLE狀態(tài))時,可以使用該函數(shù)進行線程間同步的操作,原理是阻塞指定的線程,直至結(jié)束。
    第2個參數(shù)用來接收執(zhí)行線程結(jié)束后的返回值。示例:
void *pointer;
pthread_join(thread, &pointer);
  • pthread_key_t
    在線程內(nèi)共享某些數(shù)據(jù),不同線程間不共享。示例如下:
pthread_key_t key_t;
pthread_key_create(&key_t, NULL);
// 設(shè)置要共享的數(shù)據(jù)    
pthread_setspecific(key_t, @"Hello World");
NSString *str = (__bridge NSString *)(pthread_getspecific(key_t));
NSLog(@"%@", str);

通常在同一個線程的不同函數(shù)中使用這種方式共享數(shù)據(jù)。

  • pthread_key_delete(pthread_key_t)
    刪除一個應(yīng)存在的pthread_key值。
  • pthread_mutex_init(pthread_mutex_t *restrict _Nonnull, const pthread_mutexattr_t *restrict _Nullable)
    初始化互斥鎖。
  • pthread_mutex_destroy(pthread_mutex_t * _Nonnull)
    銷毀互斥鎖。
  • pthread_mutex_lock(pthread_mutex_t * _Nonnull)、pthread_mutex_unlock(pthread_mutex_t * _Nonnull)
    加鎖、解鎖。
  • pthread_mutex_trylock(pthread_mutex_t * _Nonnull)
    非阻塞的加鎖,如果已經(jīng)加鎖,不會阻塞當前線程,而是會返回一個異常值。
    關(guān)于上述幾個互斥鎖的函數(shù)使用,示例如下:
pthread_mutex_t testLock;
pthread_mutex_init(&testLock, NULL); // 第2個參數(shù)為鎖的屬性配置參數(shù)
pthread_mutex_lock(&testLock); // 加鎖
/**
 省略需要互斥執(zhí)行的邏輯代碼
 */
pthread_mutex_unlock(&testLock);
  • pthread_rwlock_init(pthread_rwlock_t *restrict _Nonnull, const pthread_rwlockattr_t *restrict _Nullable)
    初始化一個讀寫鎖。
  • pthread_rwlock_destroy(pthread_rwlock_t * _Nonnull)
    銷毀讀寫鎖。
  • pthread_rwlock_rdlock(pthread_rwlock_t * _Nonnull)
    將讀寫鎖的讀權(quán)限加鎖。
  • pthread_rwlock_wrlock(pthread_rwlock_t * _Nonnull)
    將讀寫鎖的寫權(quán)限加鎖。
  • pthread_rwlock_tryrdlock(pthread_rwlock_t * _Nonnull)
    非阻塞地將讀寫鎖的讀權(quán)限加鎖。
  • pthread_rwlock_trywrlock(pthread_rwlock_t * _Nonnull)
    非阻塞地將讀寫鎖的寫權(quán)限加鎖。
  • pthread_rwlock_unlock(pthread_rwlock_t * _Nonnull)
    解鎖。
4、pthread線程間通信

pthread中通過發(fā)送信號的方式進行線程間的通信。信號的使用非常簡單,主要借助于如下兩個函數(shù):

  • sigwait(const sigset_t *restrict, int *restrict)
    該函數(shù)會阻塞當前線程等待接收信號。
  • pthread_kill(pthread_t _Nonnull, int)
    該函數(shù)用來向某個線程發(fā)送信號,第1個參數(shù)為要發(fā)送信號的線程,第2個參數(shù)為信號標識,系統(tǒng)默認定義了許多信號,可以直接使用,也可以自定義信號。返回int值用來表示發(fā)送信號的結(jié)果,0表示成功。
5、單例實現(xiàn)

pthread提供了專門的方法來保證某段邏輯在多線程中只被執(zhí)行一次,示例如下:

pthread_once_t onceToken;
void oncefunc(void) {
    NSLog(@"once");
}

void *task(void *param) {
    NSLog(@"%p", pthread_self());
    pthread_once(&onceToken, oncefunc());
    return NULL;
}

pthread_once(pthread_once_t * _Nonnull, void (* _Nonnull)(void))函數(shù)調(diào)用本身保證了執(zhí)行的互斥性,不同線程調(diào)用多次,也只會執(zhí)行一次。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容