#include #include #include #include // 线程将要执行的函数 void* print_hello(void* thread_id) { long tid; tid = (long)thread_id; printf("Hello World! It's me, thread #%ld!\n", tid); sleep(1); // 模拟长时间运行的任务 printf("Thread #%ld is finished.\n", tid); pthread_exit(NULL); } int main() { pthread_t threads[2]; int rc; long t; for(t = 0; t < 2; t++) { printf("In main: creating thread %ld\n", t); rc = pthread_create(&threads[t], NULL, print_hello, (void*)t); if(rc) { printf("Error:unable to create thread,%d\n", rc); exit(-1); } } // 等待两个线程完成 for(t = 0; t < 2; t++) { pthread_join(threads[t], NULL); } printf("Main completed. Exiting.\n"); pthread_exit(NULL); }