Multi-threaded tetralogy of pthread

Introduction to pthreads

pthread is a set of general multi-thread API, which can be used across platforms in Unix / Linux / Windows and other systems. It is written in C language and requires programmers to manage the life cycle of threads. It is difficult to use. We almost I don't use pthread, but I still come to find out.

POSIX threads (English: POSIX Threads, often abbreviated as Pthreads) is a POSIX thread standard that defines a set of APIs for creating and manipulating threads.

The library that implements the POSIX thread standard is often called Pthreads, and is generally used in Unix-like POSIX systems, such as Linux and Solaris. However, implementations on Microsoft Windows also exist, such as the third-party library pthreads-w32 that directly uses the Windows API; and using the SFU/SUA subsystem of Windows, you can use a part of the native POSIX API provided by Microsoft.

Use of pthreads

first

//
//  ViewController.m
//  pthread
//
//  Created by 差不多先生 on 2022/6/6.
//

#import "ViewController.h"
#import <pthread.h>
@interface ViewController ()

@end

@implementation ViewController
void *run(void* param) {
    
    
    
    for (NSInteger i = 0; i < 5; i++) {
    
    
        NSLog(@"%ld-> %@", i, [NSThread currentThread]);
    }
        return NULL;
}
- (void)viewDidLoad {
    
    
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    pthread_t myThread;
    int res = pthread_create(&myThread, NULL, run, NULL);
    if (res == 0) {
    
    
        NSLog(@"创建线程成功!");
    }
    // 线程结束后释放所有资源
    pthread_detach(myThread);
    NSLog(@"%@", [NSThread currentThread]);
}

@end

insert image description here

It can be seen that the thread here is carried out at the same time as the main thread. The meaning of the four parameters:
&myThread is the thread object, a pointer to the thread identifier
The second is the thread attribute, the default is NULL
The third run indicates the pointer to the function , the newly created thread starts running from the address of the run function.
The fourth default is NULL. If the above function requires parameters, pass in the address

some other uses

pthread_create() 创建一个线程

pthread_exit() 终止当前线程

pthread_cancel() 中断另外一个线程的运行

pthread_join() 阻塞当前的线程,直到另外一个线程运行结束

pthread_attr_init() 初始化线程的属性

pthread_attr_setdetachstate() 设置脱离状态的属性(决定这个线程在终止时是否可以被结合)

pthread_attr_getdetachstate() 获取脱离状态的属性

pthread_attr_destroy() 删除线程的属性

pthread_kill() 向线程发送一个信号

Guess you like

Origin blog.csdn.net/chabuduoxs/article/details/125153978