Skip to content

Commit c082d7f

Browse files
committed
[gdb] Initialize main_thread_id earlier
I wrote a patch using is_main_thread (), and found it returning false in the main thread due to main_thread_id not being initialized yet. Initialization currently takes place in _initialize_run_on_main_thread, but that's too late for earlier uses. Fix this by initializing, either: - when entering main, or - on an earlier first use. Tested on x86_64-linux. Approved-By: Tom Tromey <[email protected]>
1 parent 3c3e54d commit c082d7f

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

gdb/gdb.c

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,17 @@
1919
#include "defs.h"
2020
#include "main.h"
2121
#include "interps.h"
22+
#include "run-on-main-thread.h"
2223

2324
int
2425
main (int argc, char **argv)
2526
{
27+
/* The first call to is_main_thread () should be from the main thread.
28+
If this is the first call, then that requirement is fulfilled here.
29+
If this is not the first call, then this verifies that the first call
30+
fulfilled that requirement. */
31+
gdb_assert (is_main_thread ());
32+
2633
struct captured_main_args args;
2734

2835
memset (&args, 0, sizeof args);

gdb/run-on-main-thread.c

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,12 +94,24 @@ run_on_main_thread (std::function<void ()> &&func)
9494
serial_event_set (runnable_event);
9595
}
9696

97+
#if CXX_STD_THREAD
98+
static bool main_thread_id_initialized = false;
99+
#endif
100+
97101
/* See run-on-main-thread.h. */
98102

99103
bool
100104
is_main_thread ()
101105
{
102106
#if CXX_STD_THREAD
107+
/* Initialize main_thread_id on first use of is_main_thread. */
108+
if (!main_thread_id_initialized)
109+
{
110+
main_thread_id_initialized = true;
111+
112+
main_thread_id = std::this_thread::get_id ();
113+
}
114+
103115
return std::this_thread::get_id () == main_thread_id;
104116
#else
105117
return true;
@@ -111,7 +123,12 @@ void
111123
_initialize_run_on_main_thread ()
112124
{
113125
#if CXX_STD_THREAD
114-
main_thread_id = std::this_thread::get_id ();
126+
/* The variable main_thread_id should be initialized when entering main, or
127+
at an earlier use, so it should already be initialized here. */
128+
gdb_assert (main_thread_id_initialized);
129+
130+
/* Assume that we execute this in the main thread. */
131+
gdb_assert (is_main_thread ());
115132
#endif
116133
runnable_event = make_serial_event ();
117134
add_file_handler (serial_event_fd (runnable_event), run_events, nullptr,

0 commit comments

Comments
 (0)