GDB debugs multithreading

Thread viewing

First create two threads:

#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
 
void* pthread_run1(void* arg)
{
    (void)arg;
 
    while(1)
    {
        printf("I am thread1,ID: %d\n",pthread_self());
        sleep(1);
    }
}
 
void* pthread_run2(void* arg)
{
    (void)arg;
 
    while(1)
    {
        printf("I am thread2,ID: %d\n",pthread_self());
        sleep(1);
    }
}
 
 
int main()
{
 
    pthread_t tid1;
    pthread_t tid2;
 
    pthread_create(&tid1,NULL,pthread_run1,NULL);
    pthread_create(&tid2,NULL,pthread_run2,NULL);
 
    printf("I am main thread\n");
 
    pthread_join(tid1,NULL);
    pthread_join(tid2,NULL);
    return 0;
}
Copy the code

In this program, two new threads are created. The main thread is the main thread, and two new threads are created

Command line view:

/ / to view the current running process ps aux | grep a.out / / check the currently running process of lightweight ps - aL | grep a.out / / view the relationship between the main thread and new thread pstree -p main thread idCopy the code

View the thread stack structure

  1. Get thread ID
  2. Run the PS stack thread ID command to view the stack structure

Use GDB to view thread information

Attach the process to the GDB debugger to see if a new thread has been created: GDB Attach main thread ID

View some information about the thread

View the process: info inferiors //2. View the thread: info threads //3. //4. Switch threads: thread n (n represents the number of threads)Copy the code

Debug multithreading using GDB

When the program is not started, the thread has not yet executed, at this time using GDB to debug multithreading and debugging ordinary programs, by setting breakpoints, run, view information, etc., I will not demonstrate here, and finally add the debug thread command

To set breakpoints

//1. Set breakpoint: break line number/function name //2Copy the code

A function that executes thread 2 to continue running until the breakpoint

1. Thread apply 1-n n 2. Restart the program to run at the breakpoint: rCopy the code

Run only the current thread

1. Set scheduler-locking on. Run: nCopy the code

All threads execute concurrently

Set scheduler-locking off 2. Run: nCopy the code

Summary of debugging multithreaded commands