1.簡介
pthread 是屬於 POSIX 多線程開發框架。它是c語言提供的一個跨平臺的多線程解決方案。由於其在iOS編程中,操作比較麻煩,一般不用,這裏介紹僅僅作爲了解。
2.pthread的使用
通過以下函數創建pthread,在C語言中類型的結尾通常 _t/Ref,而且不需要使用 *:
int pthread_create(pthread_t * __restrict, const pthread_attr_t * __restrict,
void *(*)(void *), void * __restrict);
參數:
1. pthread_t * __restrict 線程代號的地址
2. onst pthread_attr_t * __restrict 線程的屬性
3. 調用函數的指針
- void *(*)(void *)
- 返回值 (函數指針)(參數)
- void * 和 OC 中的 id 是等價的
4. void * __restrict :傳遞給該函數的參數
返回值:
- 如果是0,表示正確
- 如果是非0,表示錯誤碼
3.代碼實戰:
#import "ViewController.h"
#import <pthread.h>
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSString *str = @"MR";
pthread_t thread;
pthread_create(&thread, NULL, &demo, (__bridge void *)(str));
}
void* demo(void* params)
{
NSString *str = (__bridge NSString *)(params);
for (int i = 0 ; i < 100; i++) {
NSLog(@"%@",str);
}
return NULL;
}
@end
__bridge(橋接)
- 在 ARC 開發中,如果設計到和 C 語言中相同的數據類型進行轉換時,需要使用 __bridge “橋接”
- 在 OC 中,如果是 ARC 開發,編譯器會在編譯的時候,自動根據代碼結構,添加 retain, release, autorelease
- ARC 只負責 OC 部分的代碼,不負責 C 的代碼,如果 C 語言的框架出現 retain/create/copy 字樣的函數,都需要release
運行結果