指针用法
来源:互联网 发布:杭州宇石网络 编辑:程序博客网 时间:2024/06/05 03:05
指针用法
(void*) 1
等的使用
(void*) C
(C是常数)实际上就是一个普通的强制类型装换,即把常数装换为指针类型,并且具体类型没有指定。在有的场合把参数转换为地址,使用地址传递,来达到一些效果。
- 在创建线程的时候,
pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void*(*start_rtn)(void*), void *restrict arg)
最后一个参数传入新线程的参数地址,当我们使用下面的代码来新建线程的时候,可能不会达到预期的效果。
void* start_rtn(void* arg){ printf("%dth thread.\n", *(int*)arg); return ((void*) 0); } int main(){ pthread_t tid[5]; for(int i = 0;i < 5; ++i){ if (prhread_create(tid+ i, NULL, start_rtn, &i) != 0){ printf("create new thread failed.\n"); exit(1); } } for(int i = 0;i < 5; ++i){ if (prhread_join(tid[i], NULL) != 0){ printf("join failed.\n"); exit(1); } } return 0; }
- 分析:这样使用会有个问题,线程里面的输出值不确定,决定于新线程开始运行的时间。因为在创建新线程的时候给start_rtn传入的值是变量i的地址,在5个线程中都不会变。但是i的值是改变的。因此当线程开始运行的时候,不知道i里面的值会是多少,因而不能打印出这是第几个创建的线程(在Ubuntu14.04里面测试的时候,新线程在所有线程创建之后再开始运行,因此5个线程答应的都是第5个线程)。
- 当修改为下面的情况的时候,可以正常运行,其方法在于先将整型值强制转换为指针型,把值当作地址传递到调用函数,然后在被调函数中在转换成int型—>利用指针传递值:
void* start_rtn(void* arg){ //*(int*)arg-->(int)arg printf("%dth thread.\n", (int)arg); return ((void*)0); } int main(){ pthread_t tid[5]; for(int i = 0;i < 5; ++i){ //&i -->(void*)i if (prhread_create(tid+ i, NULL, start_rtn, (void*)i) != 0){ printf("create new thread failed.\n"); exit(1); } } for(int i = 0;i < 5; ++i){ if (prhread_join(tid[i], NULL) != 0){ printf("join failed.\n"); exit(1); } } return 0; }
- 在创建线程中,需要传入不同的值的时候,可以将值转换成为(void*)指针。
阅读全文
0 0
- 指针用法
- 指针用法
- 指针用法
- 指针用法
- 指针用法
- 指针用法
- 指针的指针用法理解
- 指针的指针的用法
- 指针的用法
- 双重指针的用法
- 指针的用法
- 函数指针的用法
- 指针在一点用法
- this指针的用法
- 函数指针的用法
- 函数指针的用法
- this指针用法
- 智能指针用法
- Struts2 的 struts.xml 配置中 namespace 的使用
- 1308 音乐会的等待/诺诺的队列 单调栈 题解
- ShaderWeaver使用教程-使用马赛克
- PHP入门-数组的定义与使用
- numpy的用法part1
- 指针用法
- 布隆过滤器原理
- 打赏博主
- Sketch文件转成PSD格式 手把手教程
- 文章标题
- PHP入门-面向对象
- Python Dataframe ——指定多列去重、求差集
- c++入门笔记(6)变量
- C# 委托