奥利喵 2015-06-04 01:12 采纳率: 100%
浏览 2938
已采纳

新手:thread_create()线程创建和输出的问题

#include
#include
#include
#include

#define NUM_THREADS 8

void PrintHello(void *args)
{
int thread_arg;
sleep(1);
thread_arg = (int)(
((int*)args));
printf("Hello from thread %d\n", thread_arg);
return NULL;
}

int main(void)
{
int rc,t;
pthread_t thread[NUM_THREADS];

for( t = 0; t < NUM_THREADS; t++)
{
    printf("Creating thread %d\n", t);
    rc = pthread_create(&thread[t], NULL, PrintHello, &t);
    if (rc)
    {
        printf("ERROR; return code is %d\n", rc);
        return EXIT_FAILURE;
    }
}
sleep(5);
for( t = 0; t < NUM_THREADS; t++)
    pthread_join(thread[t], NULL);
return EXIT_SUCCESS;

}

Creating thread 0
Creating thread 1
Creating thread 2
Creating thread 3
Creating thread 4
Creating thread 5
Creating thread 6
Creating thread 7
Hello from thread 8
Hello from thread 8
Hello from thread 8
Hello from thread 8
Hello from thread 8
Hello from thread 8
Hello from thread 8
Hello from thread 8

这个输出结果搞不明白,不是应该是下面这样吗
Creating thread 0
Creating thread 1
Creating thread 2
Creating thread 3
Creating thread 4
Creating thread 5
Creating thread 6
Creating thread 7
Hello from thread 0
Hello from thread 1
Hello from thread 2
Hello from thread 3
Hello from thread 4
Hello from thread 5
Hello from thread 6
Hello from thread 7

搞不懂为什么。。。

  • 写回答

8条回答 默认 最新

  • 一枪尽骚丶魂 2015-06-04 01:46
    关注

    刚刚我自己本地测试了一下。
    sleep(1);
    thread_arg = (int)(((int*)args));
    改为
    int thread_arg = -1;
    thread_arg = *(int *)arg;
    sleep(1);
    可以满足你的需求

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(7条)

报告相同问题?

悬赏问题

  • ¥15 链接问题 C++LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接