POSIX线程(在pthread_create和pthread_join函数) [英] posix threads (pthread_create and pthread_join)

查看:216
本文介绍了POSIX线程(在pthread_create和pthread_join函数)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要学习Unix C和做一些练习练习。我的工作目前存在的问题涉及到POSIX线程(主要是在pthread_create(),并在pthread_join())

I am trying to learn Unix C and doing some exercises for practice. The current problem I am working on involves POSIX threads (mainly pthread_create() and pthread_join())

这道题反复打印的Hello World使用两个线程。一个线程是打印你好的1000倍,而第二个线程打印世界1000倍。主程序/线程等待两个线程在继续之前完成。

The problem asks to repeatedly print "Hello World" using two threads. One thread is to print "Hello" 1000 times, while the second thread prints "World" 1000 times. The main program/thread is to wait for the two threads to finish before proceeding.

下面是我现在所拥有的。

Here is what I have right now.

#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;
}

这似乎并没有完全工作。如预期它打印你好。但世界是不是在所有打印。好像第二个线程不运行在所有。不知道我是用在pthread_join正确。我的目的是让主线程等待这两个线程的练习要求。

This does not seem to work fully. It prints "Hello" as expected. But "World" is not printed at all. Seems like the second thread is not running at all. Not sure I am using pthread_join correctly. My intention is for the main thread to "wait" for these two threads as the exercise asks.

任何帮助将是AP preciated。

Any help would be appreciated.

推荐答案

是什么让你觉得它没有运行两个线程?我认为输出只是尖叫过去,你的速度太快注意到 - 你会得到一个块大批每个线程的输出

What makes you think it isn't running both threads? I think the output is just screaming past you too quickly to notice -- you're going to get a large number of each thread's output in a single block.

尝试输出重定向到一个文件和审查实际上得到打印的内容。

Try redirecting the output to a file and reviewing what actually got printed.

这篇关于POSIX线程(在pthread_create和pthread_join函数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆