2011-06-24 48 views
0

我想学习Unix C并为练习做一些练习。我正在处理的当前问题涉及POSIX线程(主要是pthread_create()和pthread_join())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; 
} 

这似乎没有充分发挥作用。它按预期打印“你好”。但“世界”根本没有印。似乎第二个线程根本没有运行。不知道我正在使用pthread_join。正如练习所要求的,我的意图是让主线程“等待”这两个线程。

任何帮助,将不胜感激。

+0

似乎对我很好,并按预期工作。你可能想在你的线程函数的最后加上'return NULL'。 – JackOfAllTrades

+0

要评论你的代码,NULL通常被定义为“(void *)0”,所以它有点愚蠢的使用两者。我建议NULL - 不保证所有系统上的空指针都被表示为0,而NULL将被定义为适当的值。 –

回答

7

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

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

2

我刚刚运行您的代码。

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

适用于Ubuntu 10.10和gcc-4.5.2。仔细检查你的编译和你的输出。