Reputation: 339
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.
Upvotes: 0
Views: 1557
Reputation: 39797
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.
Upvotes: 7
Reputation: 12727
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.
Upvotes: 2