How to restrict gdb debugging to one thread at a time
I want to debug a multi-threaded program by controlling which threads execute when. I am using C++ and gdb. I have two threads besides the main thread (for the example program) and I want to debug one thread while keeping the other stopped.
Here is the example program I wrote:
#include <iostream>
#include <pthread.h>
#include <stdlib.h>
#define NUM_THREADS 2
using namespace std;
void * run (void *) {
for (int i = 0; i < 3; ++i) {
sleep(1);
cout << i << " " << pthr开发者_JS百科ead_self() << endl;
}
pthread_exit(NULL);
}
int main (int argc, char** argv) {
cout << "Start..." << endl;
int rc;
pthread_t threads[NUM_THREADS];
for (int i = 0; i < NUM_THREADS; ++i) {
rc = pthread_create(&threads[i], NULL, run, NULL);
if (rc) {
cout << "pthread_create returned error: " << rc << endl;
exit(-1);
}
}
pthread_exit(NULL);
}
I run gdb and set the breakpoint at line with sleep(1)
. Then I run the program. I get three threads (thread 2 and 3 are pthreads) and the program is at thread 2 (waiting at sleep(1)
). Now, I want to keep thread 3 wherever it is, and keep stepping through thread 2 (by executing c
in gdb).
What I have tried is set scheduler-locking on
, but it does not seem to work as I expected. I am in thread 2, I set scheduler-locking on
, continue
a couple times (so far so good, I am still in thread 2), switch to thread 3, set scheduler-locking on
, continue
, and for some reason, I am back in thread 2... when I should not be (according to my understanding). Is there something I am missing?
As TazMainiac said, scheduler-locking is useful for single stepping, but the "mode" must be set to "step".
set scheduler-locking step
You can refer the link provided by TazMainiac which mentions the same:
http://ftp.gnu.org/old-gnu/Manuals/gdb-5.1.1/html_node/gdb_39.html
The step mode optimizes for single-stepping. It stops other threads from "seizing the prompt" by preempting the current thread while you are stepping.
It looks like scheduler-locking is only useful when you single-step or next. Once you continue your current thread, they all run, and the next thread to hit a break point will grab the prompts. At least, that's my interpretation of the manual:
http://ftp.gnu.org/old-gnu/Manuals/gdb-5.1.1/html_node/gdb_39.html
So, once you are in thread 3, the other threads are stopped, and as long as you step/next, they will not run. But once you continue, they all run, and the next thread (2 in your example) that hits the break point in the sleep(1) will grab the prompt.
Maybe let all the threads hit the sleep, but then only continue one of them at a time.
精彩评论