免费注册 查看新帖 |

Chinaunix

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

[C] 求助线程问题 [复制链接]

论坛徽章:
1
IT运维版块每日发帖之星
日期:2015-09-11 06:20:00
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2010-07-26 22:32 |只看该作者 |倒序浏览
有如下一段线程的代码:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

void * thfn(void *argv)
{
        int i;
        for(i=0;i<3;i++)
                printf("this is new thread process.\n");
}

int main(void)
{
        pthread_t id;
        int i , ret;
        ret=pthread_create(&id,NULL,thfn,NULL);
        if(ret !=0)
        {
                printf("create thread error\n");
                exit(1);
        }
        for(i=0;i<3;i++)
        {
                printf("this is main thread process\n");
        }
        pthread_join(id,NULL);
        return 0;
}

编译运行后结果为:
this is main thread process
this is main thread process
this is main thread process
this is new thread process.
this is new thread process.
this is new thread process.

网上说每次运行的结果都不一样,但我所不解的是在我的系统里为什么每次运行的结果都是一样的,每次都是主线程先运行,难道没有发生cpu抢占吗?

论坛徽章:
0
2 [报告]
发表于 2010-07-27 09:46 |只看该作者
你开的线程数太少了,估计CPU还没调度线程呢,你程序就over了,多开几个OK~~

论坛徽章:
0
3 [报告]
发表于 2010-07-27 10:00 |只看该作者
没必要太较真的,肯定是随机的。。

论坛徽章:
1
IT运维版块每日发帖之星
日期:2015-09-11 06:20:00
4 [报告]
发表于 2010-07-27 10:38 |只看该作者
回复 2# davelv


    谢谢,多开几个线程随机性就看出来了。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP