免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2136 | 回复: 1
打印 上一主题 下一主题

[Linux] 这个程序中为什么子线程中传入的参数不对? [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2016-08-13 23:04 |只看该作者 |倒序浏览
void* thr_fn(void* arg)
{
    unsigned int seq = *(unsigned int *)arg;
    fprintf(stderr, "th_fun thread %lx seq %u\n", pthread_self(), seq);
    pthread_exit(NULL);
}

int main()
{   
    pthread_t tid[5];
    unsigned int i;

    for(i = 0; i < 5; i++)
    {
        pthread_create(tid + i, NULL, thr_fn, (void *)&i))
        fprintf(stderr, "thread %lx seq %u\n", tid[i], i);
    }
    return 0;
}

结果是
thread 7f3803ba6700 seq 0
thread 7f38033a5700 seq 1
thread 7f3802ba4700 seq 2
thread 7f38023a3700 seq 3
thread 7f3801ba2700 seq 4
th_fun thread 7f38023a3700 seq 0 (序号应为3)
th_fun thread 7f3801ba2700 seq 0 (序号应为4)
th_fun thread 7f3803ba6700 seq 0
th_fun thread 7f38033a5700 seq 1
th_fun thread 7f3802ba4700 seq 2

centos 7.2 gcc 4.8.5
应该怎样修改程序子线程才能传入正确的序号?

论坛徽章:
95
程序设计版块每日发帖之星
日期:2015-09-05 06:20:00程序设计版块每日发帖之星
日期:2015-09-17 06:20:00程序设计版块每日发帖之星
日期:2015-09-18 06:20:002015亚冠之阿尔艾因
日期:2015-09-18 10:35:08月度论坛发贴之星
日期:2015-09-30 22:25:002015亚冠之阿尔沙巴布
日期:2015-10-03 08:57:39程序设计版块每日发帖之星
日期:2015-10-05 06:20:00每日论坛发贴之星
日期:2015-10-05 06:20:002015年亚冠纪念徽章
日期:2015-10-06 10:06:482015亚冠之塔什干棉农
日期:2015-10-19 19:43:35程序设计版块每日发帖之星
日期:2015-10-21 06:20:00每日论坛发贴之星
日期:2015-09-14 06:20:00
2 [报告]
发表于 2016-08-13 23:30 |只看该作者
本帖最后由 MMMIX 于 2016-08-13 23:44 编辑

回复 1# riryka


    多个线程同时(读/写)访问变量 i,没有同步,出现这种结果也不奇怪。

应该怎样修改程序子线程才能传入正确的序号?


传入 i 的值,而不是它的地址:

pthread_create(tid + i, NULL, thr_fn, (void *)&i);

改成

pthread_create(tid + i, NULL, thr_fn, (void *)i);

然后 thr_fn 也做对应修改。

另外,i 的类型最好改为 intptr_t 或者 uintptr_t。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP