posix线程(pthread_create和pthread_join)

use*_*752 0 c unix multithreading posix

我正在努力学习Unix C并做一些练习练习.我正在处理的当前问题涉及POSIX线程(主要是pthread_create()和pthread_join())

该问题要求使用两个线程重复打印"Hello World".一个线程是打印"Hello"1000次,而第二个线程打印"World"1000次.主程序/线程是在继续之前等待两个线程完成.

这就是我现在所拥有的.

#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>

void *print_hello(void *arg)
{
  int iCount;
  for(iCount = 0; iCount < 1000; iCount++)
  {
     printf("Hello\n");
  }
}

void *print_world(void *arg)
{
   int iCount;
   for(iCount = 0; iCount < 1000; iCount++)
   {
      printf("World\n");
   }
}

int main(void)
{
  /* int status; */
  pthread_t thread1;
  pthread_t thread2;

  pthread_create(&thread1, NULL, print_hello, (void*)0);
  pthread_create(&thread2, NULL, print_world, (void*)0);

  pthread_join(thread1, NULL);
  pthread_join(thread2, NULL);

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

这似乎没有完全发挥作用.它按预期打印"Hello".但"世界"根本没有印刷.好像第二个线程根本没有运行.不确定我是否正确使用pthread_join.我的目的是让主线程"等待"这两个线程,因为练习要求.

任何帮助,将不胜感激.

mah*_*mah 7

是什么让你觉得它没有运行两个线程?我认为输出只是尖叫过去你太快注意到 - 你将在一个块中获得大量的每个线程的输出.

尝试将输出重定向到文件并查看实际打印的内容.