0

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())

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

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.

Any help would be appreciated.

2
  • Seems OK to me, and works as expected. You might want to add return NULL at the end of your thread functions though. Commented Jun 24, 2011 at 19:07
  • To comment on your code, NULL is usually defined as "(void*)0", so its a bit silly to use both. I'd suggest NULL - there is no guarantee that a null pointer is represented as 0 on all systems, while NULL will be defined to the appropriate value. Commented Jun 25, 2011 at 2:19

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

Comments

2

I just ran your code.

$ gcc ./foo.c -pthread
$ ./a.out | grep World | wc -l
1000
$ ./a.out | grep Hello | wc -l
1000

Works for me on Ubuntu 10.10 with gcc-4.5.2. Double check your compilation and your output.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.