Skip to content

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

@vseguip

Description

@vseguip

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions