奥利喵 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 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog