4

我使用的是 Ubuntu 10.10,Code::Blocks 和 GCC 4.2。

我写了这样的代码:

#include <iostream>
#include <stdlib.h>
#include <pthread.h>

using namespace std;

void *thread1proc(void* param){
    while(true)
    cout << "1";

    return 0;
}

int main(){
    pthread_t thread1;

    pthread_create(&thread1,NULL,thread1proc,NULL);
    pthread_join(thread1,NULL);

    cout << "hello";
}

Main 启动,创建线程。但是(对我来说)奇怪的是 main 不会继续运行。我希望在屏幕上和程序结束时看到“你好”消息。因为在 Windows 中,在 Delphi 中它对我有用。如果“main”也是一个线程,为什么它不继续运行呢?是关于 POSIX 线程的吗?

谢谢你。

4

2 回答 2

8

pthread_join will block until thread1 completes (calling pthread_exit or returning), which (as it has an infinite loop) it never will do.

于 2010-12-06T20:19:17.480 回答
3

It stops because you call pthread_join and the thread you are joining "to" has an infinite loop.

From that link:

The pthread_join() function suspends execution of the calling thread until the target thread terminates, unless the target thread has already terminated.

于 2010-12-06T20:20:07.303 回答