thread2.cpp 878 Bytes
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

// 线程将要执行的函数
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);
}