How to restrict gdb debugging to one thread at a time

Viewed 30059

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 << " " << pthread_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?

2 Answers
Related