溫馨提示×

linux pthread_join如何正確使用

小樊
103
2024-12-29 12:11:25
欄目: 智能運維

pthread_join是Linux中用于等待一個或多個線程完成的函數

下面是一個簡單的示例,展示了如何使用pthread_join正確等待線程完成:

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

// 線程函數
void *thread_function(void *arg) {
    int thread_id = *(int *)arg;
    printf("Thread %d is running.\n", thread_id);
    sleep(1); // 模擬線程工作
    printf("Thread %d is finished.\n", thread_id);
    return NULL;
}

int main() {
    pthread_t threads[5]; // 創建5個線程
    int thread_ids[5];  // 存儲線程ID

    // 創建線程并存儲它們的ID
    for (int i = 0; i < 5; i++) {
        thread_ids[i] = i;
        if (pthread_create(&threads[i], NULL, thread_function, &thread_ids[i]) != 0) {
            perror("Failed to create thread");
            exit(EXIT_FAILURE);
        }
    }

    // 等待所有線程完成
    for (int i = 0; i < 5; i++) {
        if (pthread_join(threads[i], NULL) != 0) {
            perror("Failed to join thread");
            exit(EXIT_FAILURE);
        }
    }

    printf("All threads have finished.\n");
    return 0;
}

在這個示例中,我們創建了5個線程,并將它們的ID傳遞給每個線程。然后,我們使用pthread_join等待每個線程完成。當所有線程完成后,我們打印一條消息表示所有線程已完成。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女