Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dispatching on main queue doesn't seem to actually run on main thread. #20

Open
vseguip opened this issue Apr 26, 2023 · 7 comments
Open

Comments

@vseguip
Copy link

vseguip commented Apr 26, 2023

I've created a more or less minimal example (based on the dispatch example) which shows that using exec_async on the main queue causes the closure to be executed on a different thread than the main thread:

extern crate dispatch;

use std::thread;
use std::process::exit;
use dispatch::{Queue, QueuePriority};
use objc::{{sel, sel_impl, msg_send, class}, runtime::{BOOL, YES, NO}};

pub fn is_main_thread() -> bool {
    unsafe {
        let thread = class!(NSThread);
        let b : BOOL = msg_send![thread, isMainThread];
        match b {
            YES => true,
            NO => false
        }
    }
}

fn test_on_main(queue: Queue) {

    queue.clone().exec_async(move || {
        let main = Queue::main();
        main.exec_async(|| {
            println!("Running from {:?} isMainThread? {}", thread::current().name(), is_main_thread());
            exit(0);
        });
    });
}

fn main() {
    // Read from stdin on a background queue so that the main queue is free
    // to handle other events. All printing still occurs through the main
    // queue to avoid jumbled output.
    cacao::utils::activate_cocoa_multithreading();
    println!("Initial Thread {:?} isMainThread? {}", thread::current().name(), is_main_thread());
    test_on_main(Queue::global(QueuePriority::Default));

    unsafe {
        dispatch::ffi::dispatch_main();
    }
}

Expected output:
Initial Thread ThreadId(1) isMainThread? true
This is another queue can execute on any thread ThreadId(X) isMainThread? false
Running from ThreadId(1) isMainThread? true

Actual output:
Initial Thread ThreadId(1) isMainThread? true
This is another queue can execute on any thread ThreadId(2) isMainThread? false
Running from ThreadId(3) isMainThread? false

@madsmtm
Copy link

madsmtm commented Apr 26, 2023

Simpler reproducer:

use std::process::exit;
use std::thread;

use dispatch::Queue;
use objc::runtime::{Object, BOOL, NO};
use objc::{class, msg_send};

fn activate_cocoa_multithreading() {
    unsafe {
        let thread: *mut Object = msg_send![class!(NSThread), new];
        let _: () = msg_send![thread, start];
    }
}

fn is_main_thread() -> bool {
    unsafe {
        let thread = class!(NSThread);
        let b: BOOL = msg_send![thread, isMainThread];
        b != NO
    }
}

fn log(message: &str) {
    println!(
        "{message}: {:?} isMainThread? {}",
        thread::current().id(),
        is_main_thread()
    );
}

fn main() {
    activate_cocoa_multithreading();
    log("main");

    Queue::main().exec_async(|| {
        log("exec_async");
        exit(0);
    });

    unsafe {
        dispatch::ffi::dispatch_main();
    }
}

Which makes me suspect the issue is actually with dispatch_main?

@madsmtm
Copy link

madsmtm commented Apr 26, 2023

Even simpler reproducer showing that the problem is not with Objective-C in any way:

use std::process;
use std::thread;

use dispatch::Queue;
use libc::pthread_main_np;

fn log(message: &str) {
    println!(
        "{message}: {:?} / main={}",
        thread::current().id(),
        unsafe { pthread_main_np() } != 0,
    );
}

fn main() {
    log("main");

    Queue::main().exec_async(|| {
        log("exec_async");
        process::exit(0);
    });

    unsafe {
        dispatch::ffi::dispatch_main();
    }
}

@madsmtm
Copy link

madsmtm commented Apr 26, 2023

Yet again, in C this time:

#include <stdio.h>
#include <stdlib.h>
#include <dispatch/dispatch.h>
#include <pthread/pthread.h>
// #import <CoreFoundation/CoreFoundation.h>

int main() {
  fprintf(stderr, "main: %i\n", pthread_main_np());

  dispatch_async(dispatch_get_main_queue(), ^{
    fprintf(stderr, "dispatch_async: %i\n", pthread_main_np());
    sleep(1);
    exit(0);
  });

  dispatch_main();
  // CFRunLoopRun();
}

If you replace the dispatch_main with CFRunLoopRun, both threads will show up as the main thread, showing that the problem is indeed in dispatch_main (which is a good reason for not making that safe in the future!).

@vseguip
Copy link
Author

vseguip commented Apr 27, 2023

Ok so it looks like an upstream issue, do you know where I can file a bug? It seems pretty serious that dispatch_main causes main queue to violate the most important contract it has.

@madsmtm
Copy link

madsmtm commented Apr 27, 2023

I think there is some way, if you have an Apple Developer account, to file an issue with them? Or maybe you should just ask on the Apple forums? Or maybe, if you can translate the question into Swift, on their forums, they might know more?

Getting into contact with Apple devs is not something I've ever tried myself though, sorry I can't help you more on that.

@vseguip vseguip changed the title Dispatching on main queu doesn't seem to actually run on main thread. Dispatching on main queue doesn't seem to actually run on main thread. Apr 28, 2023
@vseguip
Copy link
Author

vseguip commented Apr 28, 2023

I tried your C example but it does seem to do the right thing with dispatch_main (tried in GCC and clang)

$ gcc dispatch_is_broken.c  -o dispatch_is_broken
$ ./dispatch_is_broken
main: 1
dispatch_async: 1
$ clang dispatch_is_broken.c  -o dispatch_is_broken_clang
$./dispatch_is_broken_clang
main: 1
dispatch_async: 1

@madsmtm
Copy link

madsmtm commented Apr 29, 2023

Huh, try recreating the nested example you gave first, but in C? Might be because I'm running the fairly old macOS 10.14 that I experience the bug without nesting the two queues?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants