使用pthread和指针类型转换在C++中的几点要注意的

本文详细介绍了在C++代码中混合使用C代码以创建线程的方法,包括如何正确地进行指针转换以避免编译错误,以及在使用pthread库时的回调函数定义和参数传递技巧。通过示例代码展示了如何实现多个参数的传入,以及使用gcc和g++编译器的不同体验。

今天打算在main.cpp中加一段C代码,目的是开一个线程来测试一些接口。But,不是不知道,一试吓一跳,一段在用gcc编译通过的代码移植到main.cpp中去,却编译报错了。main.cpp是用g++编译的。于是在各种地方搜索,最后问题得以解决,记录之。

C++中不能像C那样例如:

int *a;
char *b;
a = b;                     //correct in gcc, but error in g++
a = (int *)b;              //correct in gcc, but error in g++
a = static_cast<int *>(b); //correct in g++, cast char* b to int*

所以在强转的时候要注意了。

另外在使用pthread的时候,pthread_create的用法和回调函数的定义形式应该如下:

Source file: test.c

#include <stdio.h>
#include <pthread.h>
#include <stdlib.>
#include <unistd.h>

typedef struct student { //目的是可以传入多个参数给子线程
    int id;
    char name[16];
} student;

void* function(void* argument); //回调函数必须是 void* f(void* a)形式

void* function(void* argument) //定义
{
    #ifdef __cplusplus
    student *tmp = static_cast<student *>(argument);
    #else
    student *tmp = argument;
    #endif

    printf("id is [%d], name is [%s]\n", tmp->id, tmp->name);
    fflush(stdout);

    exit(0);
}

int main() {
    pthread_t pid;
    student a = { 18, "zhangsan\0"};
    
    pthread_create(&pid, NULL, &function, &a); //第三个参数的写法为&f形式,并且f为" void* f(void* a) "

    sleep(2); //主线程阻塞2s以等待子线程完成printf打印完成
    return 0;
}

Compile command:

$ gcc -g -Wall test.c

 Output:

$ ./a.exe
id is [18], name is [zhangsan]

从以上代码可以看出,C代码中的pthread相关代码用g++来编译时,会遇到不少关于指针转换的问题,就是因为C++中不允许隐式转换(implicitly cast)。

而上述代码原型适应在C++代码中加入C代码的创建线程,并且传入多个参数(因为传入结构体,那么结构体中可包含很多参数)。

而用gcc的情况下使用pthread就简单多了。

转载于:https://my.oschina.net/michaelyuanyuan/blog/71500

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值