C++创建线程pthread_create和gdb的调试小记

介绍pthread_create

#include <pthread.h>
int pthread_create(pthread_t *thread,const pthread_attr *attr,void * (start_routine)(void),void *arg);
RETURN VALUE
On success,pthread_create() return 0;

第一个参数用于存放指向pthread_t 类型的指针(指向该线程tid号的地址)
第二个参数表示了线程的属性,一般以null表示默认属性
第三个参数是一个函数指针,就是线程执行的函数。这个函数返回值为void*
第四个参数表示线程传入的参数,若不传入,可用NULL填充(这个参数涉及到void*变量的强制转化)

示例:

//在Linux系统编译命令:
//gcc XXXX.cpp(源文件) -lpthread -lstdc++ -lm -g -o test

#include <iostream>
#include <pthread.h>
using namespace std;
pthread_t mythread;
void* fn (void *arg){
  int i = *((int*)arg);
  printf("i = %d \n",i);
}

int main(){
   printf("start execute \n");
   int a = 100;
   int err = pthread_create(&mythread,NULL,fn,(void*)&a);
   pthread_join(mythread,NULL);
   return 0;
}

传参数详细解释
pthread_create()的最后一个参数的为void类型的数据,表示可以向线程传递一个void数据类型的参数,线程的回调函数中可以获取改参数。该参数可以是任意类型的变量,如int型变量,一个指针,同时也可以是一个结构体。其中涉及到了void*参数的强制转换。

/*传递常量参数*/
#include <iostream>
#include <pthread.h>

using namespace std;
pthread_t mythread;
void* fn (void *arg){
  long i = (long)arg;
  printf("i = %ld \n",i);
}

int main(){
   printf("start execute \n");
   int a = 100;
   int err = pthread_create(&mythread,NULL,fn,(void*)(long)a);
   pthread_join(mythread,NULL);
   return 0;
}
/*传递指针参数*/
#include <iostream>
#include <pthread.h>
using namespace std;
pthread_t mythread;
void* fn (void *arg){
  int i = *((int*)arg);
  printf("i = %d \n",i);
}

int main(){
   printf("start execute \n");
   int a = 100;
   int err = pthread_create(&mythread,NULL,fn,(void*)&a);
   pthread_join(mythread,NULL);
   return 0;
}
gdb 调试小记

gdb test //会出现下图所示字符
在这里插入图片描述

run 命令

缩写r

  • 停止在断点处
  • 指定参数路径等

break 命令

缩写b

  • 跟行号

  • 跟函数名

  • b +offset /-offset,在当前行的前面或后面offset行停止

  • 查看断点
    info break_num
    缩写 i b

  • 删除断点
    delete break_num
    缩写 d n

单步命令

next 命令

缩写n

  • next count,执行count 条指令
  • 重复上一条命令:按下回车。即每一次重复执行上一条指令时,不需要重复输入,只需要回车即可。
    注: 报错”The program is not being run."
    程序还没有开始执行,解决方法 此时输入start即开始调试,注意不要使用run 命令

step 命令

缩写s

  • 可以进入函数
  • step count
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值