【问题标题】:PThread Creation and TerminationPThread 创建和终止
【发布时间】:2015-12-08 06:07:10
【问题描述】:

我是 使用 c 进行 Pthread 编程的新手 我碰巧从网上获取了以下代码

#include <pthread.h>
#include <stdio.h>
#define NUM_THREADS     5
void *PrintHello(void *threadid)
{
  long tid;
  tid = (long)threadid;
  printf("Hello World! It's me, thread #%ld!\n", tid);
  pthread_exit(NULL);
}

int main (int argc, char *argv[])
{
   pthread_t threads[NUM_THREADS];
    int rc;
   long t;
    for(t=0; t<NUM_THREADS; t++){
       printf("In main: creating thread %ld\n", t);
        rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
        if (rc)
         {
     printf("ERROR; return code from pthread_create() is %d\n",  rc);    
          exit(-1);
          }
    }

       /* Last thing that main() should do */
       pthread_exit(NULL);
}

每次运行上述代码时,收到的输出都会有所不同。 有什么错误原因吗?

【问题讨论】:

  • 您在此处打印线程 ID,每个线程都不同..
  • @Naresh:代码打印tfor 循环中分配的main() 的值。
  • 代码中唯一的错误是它很可能错过了原型exit()
  • 谢谢我能解决问题。

标签: c pthreads


【解决方案1】:

我不知道你的程序有什么错误。它可以完美地执行。当创建线程时,它的运行时间不在你的控制范围内,你不知道它位于哪个时间,这取决于你的操作系统。所以每个输出都是不同的

【讨论】:

  • 有没有办法监视运行时间在 main:创建线程 0 在 main:创建线程 1 在 main:创建线程 2 在 main:创建线程 3 在 main:创建线程 4 这个amin 函数的消息始终按线程 1 到 4 的顺序排列,但输出不同的是 hello world 中线程的输出。
  • 我认为这是因为在创建线程1-4时,主线程正在占用cpu,所以可以看到依次输出“In main: Creating thread1-4”。但是理论上输出会有所不同,当你创建一个线程时,它可以占用cpu并立即完成它的任务,否则它可能需要一点时间来等待cpu。所以你的混乱不是问题,只是因为你的机器没有按照你的思维方式运行。你的想法只是一种可能性,但不是全部。
猜你喜欢
  • 2013-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多