lundi 14 septembre 2020

Is it possible to make only one thread run with GDB

I'm learning how to use GDB to debug multi threading C++11 program.

Here is my test code:

void func()
{
    int i = 0;
    while (true) {
        std::cout << std::this_thread::get_id() << ": " << (i++) <<std::endl;
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    }
}

int main()
{
    std::thread t1(func);
    std::thread t2(func);
    t1.join();
    t2.join();

    return 0;
}

Well, this is quite simple: two infinite loops, each of them is executed by a thread.

I execute g++ -std=c++11 test.cpp -g -lpthread and get a binary file a.out.

After running a.out on the terminal A, I open another terminal B to attach on it with gdb: gdb -p <PID_of_a.out>.

Now the output of a.out on the terminal A is stopped as expected.

Then, I execute info thread on the terminal B:

(gdb) info threads
  Id   Target Id         Frame
* 1    Thread 0x7f3b10c24740 (LWP 62395) "a.out" 0x00007f3b10803d2d in __GI___pthread_timedjoin_ex (threadid=139891642771200, thread_return=0x0, abstime=0x0,
    block=<optimized out>) at pthread_join_common.c:89
  2    Thread 0x7f3b0faca700 (LWP 62396) "a.out" 0x00007f3b1080cc70 in __GI___nanosleep (requested_time=0x7f3b0fac9d90, remaining=0x7f3b0fac9d90)
    at ../sysdeps/unix/sysv/linux/nanosleep.c:28
  3    Thread 0x7f3b0f2c9700 (LWP 62397) "a.out" 0x00007f3b1080cc70 in __GI___nanosleep (requested_time=0x7f3b0f2c8d90, remaining=0x7f3b0f2c8d90)
    at ../sysdeps/unix/sysv/linux/nanosleep.c:28

So thread 1 is the main function, thread 2 and thread 3 are the two threads of func.

Then I execute thread 2 to switch to the thread 2.

Now, I keep typing n to make the thread 2 run.

What I want to do is to make the thread 2 run while making the thread 3 keep stopping. However, it seems that thread 3 is executed too because of typing n on the thread 2. Here is the output of the terminal A:

139891642771200: 17
139891634378496: 17
139891642771200: 18
139891634378496: 18
139891642771200: 19
139891634378496: 19
139891634378496: 20
139891634378496: 21
139891634378496: 22
139891634378496: 23
139891642771200: 20
139891634378496: 24
139891634378496: 25

You can see the last third line: 139891642771200: 20, it comes from the thread 3.

So my question is if it is possible to make only one thread run with GDB? If possible, what could I do?

Aucun commentaire:

Enregistrer un commentaire