def get_main_thread_id(unlikely_thread_id=None):
    """
    :param unlikely_thread_id:
        Pass to mark some thread id as not likely the main thread.

    :return tuple(thread_id, critical_warning)
    """
    import sys
    import os
    current_frames = sys._current_frames()
    possible_thread_ids = []
    for thread_ident, frame in current_frames.items():
        while frame.f_back is not None:
            frame = frame.f_back
        basename = os.path.basename(frame.f_code.co_filename)
        if basename.endswith(('.pyc', '.pyo')):
            basename = basename[:-1]
        if (frame.f_code.co_name, basename) in [('_run_module_as_main',
            'runpy.py'), ('run_module_as_main', 'runpy.py'), ('run_module',
            'runpy.py'), ('run_path', 'runpy.py')]:
            return thread_ident, ''
        if frame.f_code.co_name == '<module>':
            if frame.f_globals.get('__name__') == '__main__':
                possible_thread_ids.insert(0, thread_ident)
                continue
            possible_thread_ids.append(thread_ident)
    if len(possible_thread_ids) > 0:
        if len(possible_thread_ids) == 1:
            return possible_thread_ids[0], ''
        while unlikely_thread_id in possible_thread_ids:
            possible_thread_ids.remove(unlikely_thread_id)
        if len(possible_thread_ids) == 1:
            return possible_thread_ids[0], ''
        elif len(possible_thread_ids) > 1:
            return (possible_thread_ids[0], 
                'Multiple thread ids found (%s). Choosing main thread id randomly (%s).'
                 % (possible_thread_ids, possible_thread_ids[0]))
    return None, 'Unable to discover main thread id.'
