当前位置:网站首页>Pthread in the multithreaded Trilogy

Pthread in the multithreaded Trilogy

2022-06-11 03:35:00 chabuduoxs

pthread brief introduction

pthread It is a set of general multithreaded API, Can be in Unix / Linux / Windows And other systems are used across platforms , Use C Language writing , Programmers need to manage the life cycle of threads themselves , It is difficult to use , We are iOS There is little use of... In development pthread, But you can still learn about it .

POSIX Threads ( English :POSIX Threads, Often abbreviated by Pthreads) yes POSIX Thread standard for , Defines a set of methods for creating and manipulating threads API.

Realization POSIX Thread standard libraries are often referred to as Pthreads, Commonly used in Unix-like POSIX System , Such as Linux、Solaris. however Microsoft Windows There are also implementations on , For example, direct use Windows API Third party libraries implemented pthreads-w32; And the use of Windows Of SFU/SUA Subsystem , You can use part of the native software provided by Microsoft POSIX API.

pthread Use

First

//
// ViewController.m
// pthread
//
// Created by  Almost sir  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(@" Thread created successfully !");
    }
    //  Release all resources after the thread ends 
    pthread_detach(myThread);
    NSLog(@"%@", [NSThread currentThread]);
}

@end

 Insert picture description here

It can be seen that the thread here is running at the same time as the main thread , The meaning of the four parameters :
&myThread Is a thread object , Pointer to thread identifier
The second is Thread properties , The default is NULL
Third run Represents a pointer to a function , Newly created thread from run The function address starts running
Fourth default by NULL, If the above function requires parameters , Pass the address into

Some other uses

pthread_create()  Create a thread 

pthread_exit()  Terminate the current thread 

pthread_cancel()  Interrupt another thread 

pthread_join()  Block current thread , Until the end of another thread 

pthread_attr_init()  Initialize the properties of the thread 

pthread_attr_setdetachstate()  Set the out of state property ( Determines whether the thread can be combined at termination )

pthread_attr_getdetachstate()  Get out of state properties 

pthread_attr_destroy()  Delete thread properties 

pthread_kill()  Send a signal to the thread 

原网站

版权声明
本文为[chabuduoxs]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206110317155572.html