title: How to restrict gdb debugging to one thread at a time
body: <p>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. </p>
  
  <p>Here is the example program I wrote: </p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;pthread.h&gt;
  #include &lt;stdlib.h&gt;
  
  #define NUM_THREADS 2
  
  using namespace std;
  
  void * run (void *) {
    for (int i = 0; i &lt; 3; ++i) {
      sleep(1);
      cout &lt;&lt; i &lt;&lt; " " &lt;&lt; pthread_self() &lt;&lt; endl;
    }
    pthread_exit(NULL);
  }
  
  int main (int argc, char** argv) {
    cout &lt;&lt; "Start..." &lt;&lt; endl;
    int rc;
  
    pthread_t threads[NUM_THREADS];
    for (int i = 0; i &lt; NUM_THREADS; ++i) {
      rc = pthread_create(&amp;threads[i], NULL, run, NULL);
      if (rc) {
        cout &lt;&lt; "pthread_create returned error: " &lt;&lt; rc &lt;&lt; endl;
        exit(-1);
      }
    }
    pthread_exit(NULL);
  
  }
  </code></pre>
  
  <p>I run gdb and set the breakpoint at line with <code>sleep(1)</code>. Then I run the program. I get three threads (thread 2 and 3 are pthreads) and the program is at thread 2 (waiting at <code>sleep(1)</code>). Now, I want to keep thread 3 wherever it is, and keep stepping through thread 2 (by executing <code>c</code> in gdb). </p>
  
  <p>What I have tried is <code>set scheduler-locking on</code>, but it does not seem to work as I expected. I am in thread 2, I <code>set scheduler-locking on</code>, <code>continue</code> a couple times (so far so good, I am still in thread 2), switch to thread 3, <code>set scheduler-locking on</code>, <code>continue</code>, 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? </p>