GDB多线程调试总结

文章通过两个示例展示了多线程编程中可能出现的问题。第一个例子说明了未正确使用互斥锁导致的并发问题,通过gdb调试工具观察到变量a的非连续变化。第二个例子演示了死锁的情况,两个线程各自持有不同锁并尝试获取对方的锁,造成阻塞。解决方法是确保线程获取锁的顺序一致性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

demo

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <iostream>
using namespace std;
long int  a = 0;
pthread_mutex_t mutex;
pthread_mutex_t mutex2;
void* threadFunc(void *arg)
{
    // pthread_mutex_lock(&mutex);
    for(int i = 0; i < 500000; i++)
    {
        a = a+1;
    }
    // pthread_mutex_unlock(&mutex);
    // pthread_mutex_lock(&mutex2);
}
void* threadFunc2(void *arg)
{
    // pthread_mutex_lock(&mutex2);
    for(int i = 500000; i < 1000000; i++)
    {
        a = a+1;
    }
    // pthread_mutex_unlock(&mutex2);
    // pthread_mutex_lock(&mutex);
}
int main(int argc,char **argv)
{
    pthread_t thread1,thread2;
    // pthread_create(&thread1 ,NULL, threadFunc,NULL);
    pthread_create(&thread1, NULL, threadFunc, NULL);
    pthread_create(&thread2 ,NULL, threadFunc2,NULL);
    pthread_join(thread1,NULL);
    pthread_join(thread2,NULL);
    cout << "value a = " << a << endl;
    return 0;
}

1 多线程编译及调试

# 1 编译生成带符号信息的程序
g++ multhread.cpp  -g -lpthread  -o test_thread# 2 开始调试程序
gdb ./test_thread 
# 3 显示源程序
layout next

此时会显示如下:

输入下面的命令 “r”继续运行程序

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值