ios开发

iOS与多线程(九) —— pthread的使用(一)

2019-06-24  本文已影响30人  刀客传奇

版本记录

版本号 时间
V1.0 2019.06.24 星期一

前言

信号量机制是多线程通信中的比较重要的一部分,对于NSOperation可以设置并发数,但是对于GCD就不能设置并发数了,那么就只能靠信号量机制了。接下来这几篇就会详细的说一下并发机制。感兴趣的可以看这几篇文章。
1. iOS与多线程(一) —— GCD中的信号量及几个重要函数
2. iOS与多线程(二) —— NSOperation实现多并发之创建任务
3. iOS与多线程(三) —— NSOperation实现多并发之创建队列和开启线程
4. iOS与多线程(四) —— NSOperation的串并行和操作依赖
5. iOS与多线程(五) —— GCD之一个简单应用示例(一)
6. iOS与多线程(六) —— GCD之一个简单应用示例(二)
7. iOS与多线程(七) —— GCD之一个简单应用示例源码(三)
8. iOS与多线程(八) —— 多线程技术概览与总结(一)

pthread

POSIX线程(POSIX threads),简称pthreads,是线程的POSIX标准。该标准定义了创建和操纵线程的一整套API。在类Unix操作系统(Unix、Linux、Mac OS X等)中,都使用Pthreads作为操作系统的线程。Windows操作系统也有其移植版pthreads-win32


函数

1. 操纵函数

2. 同步函数

用于 mutex 和条件变量

3. 工具函数


使用示例

pthread_create

该函数的作用就是创建线程

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

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
}

/*
 函数:pthread_create
 第一个参数pthread_t *restrict:线程对象
 第二个参数const pthread_attr_t *restrict:线程属性
 第三个参数void *(*)(void *) :指向函数的指针
 第四个参数void *restrict:函数的参数
 */
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    pthread_t thread;
    int result = pthread_create(&thread, NULL,run ,NULL);
    result == 0 ? NSLog(@"success") : NSLog(@"failure");
    
    //设置子线程的状态设置为detached,则该线程运行结束后会自动释放所有资源,或者在子线程中添加 pthread_detach(pthread_self()),其中pthread_self()是获得线程自身的id
    pthread_detach(thread);
}

void *run(void *param)
{
    for (NSInteger i = 0 ; i < 10; i++) {
        NSLog(@"%zd---%@" ,i ,[NSThread currentThread]);
    }
    return NULL;
}

@end

下面看一下输出

2019-06-24 17:39:58.913279+0800 JJPthread[3869:773338] success
2019-06-24 17:39:58.913424+0800 JJPthread[3869:774430] 0---<NSThread: 0x60000130d280>{number = 3, name = (null)}
2019-06-24 17:39:58.914529+0800 JJPthread[3869:774430] 1---<NSThread: 0x60000130d280>{number = 3, name = (null)}
2019-06-24 17:39:58.915699+0800 JJPthread[3869:774430] 2---<NSThread: 0x60000130d280>{number = 3, name = (null)}
2019-06-24 17:39:58.916905+0800 JJPthread[3869:774430] 3---<NSThread: 0x60000130d280>{number = 3, name = (null)}
2019-06-24 17:39:58.917824+0800 JJPthread[3869:774430] 4---<NSThread: 0x60000130d280>{number = 3, name = (null)}
2019-06-24 17:39:58.918905+0800 JJPthread[3869:774430] 5---<NSThread: 0x60000130d280>{number = 3, name = (null)}
2019-06-24 17:39:58.919713+0800 JJPthread[3869:774430] 6---<NSThread: 0x60000130d280>{number = 3, name = (null)}
2019-06-24 17:39:58.920841+0800 JJPthread[3869:774430] 7---<NSThread: 0x60000130d280>{number = 3, name = (null)}
2019-06-24 17:39:58.923216+0800 JJPthread[3869:774430] 8---<NSThread: 0x60000130d280>{number = 3, name = (null)}
2019-06-24 17:39:58.924705+0800 JJPthread[3869:774430] 9---<NSThread: 0x60000130d280>{number = 3, name = (null)}

参考资源

1. POSIX Threads Programming
2. pthread,NSThread的使用

后记

本篇主要讲述了pThread,感兴趣的给个赞或者关注~~~

上一篇下一篇

猜你喜欢

热点阅读