wackoisgod
3/7/2018 - 3:52 AM

thread.mm

//
//  ViewController.mm
//

#import "ViewController.h"
#include <pthread.h>

mach_port_t gettid()
{
    return pthread_mach_thread_np(pthread_self());
}

@interface ViewController ()
@property (strong, nonatomic) UITextView *textView;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.textView = [[UITextView alloc] initWithFrame:self.view.frame];
    
    NSTextStorage *storage = self.textView.textStorage;
    [storage beginEditing];
    [storage.mutableString appendFormat:@"main thread is %lld\n", gettid()];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        for (int x = 0; x < 100; ++x) {
             [NSThread sleepForTimeInterval:1.0]; // just to wait ?
            printf("thread is %lld\n", gettid());
            dispatch_async(dispatch_get_main_queue(),
                           ^{
                               [storage.mutableString appendFormat:@"line %d\n", x];
                           });
        }
    
    });
    
    
    [storage.mutableString appendString:@"end\n"];
    [storage endEditing];
    
    self.textView.font = [UIFont fontWithName:@"Courier" size:18.0f];
    self.textView.editable = FALSE;
    self.textView.scrollEnabled = TRUE;
    self.textView.selectable = TRUE;
    
    NSRange range;
    range.length = 1;
    range.location = [storage.mutableString length] - 1;
    [self.textView scrollRangeToVisible:range];
    
    [self.view addSubview:self.textView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (BOOL)prefersStatusBarHidden {
    return YES;
}

@end