溫馨提示×

linux pthread在哪里初始化線程

小樊
90
2024-12-29 03:10:12
欄目: 智能運維

在Linux中,使用POSIX線程(pthread)庫時,線程的初始化是通過調用pthread_create()函數來完成的

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

void *my_thread_function(void *arg) {
    printf("Hello from the new thread!\n");
    return NULL;
}

int main() {
    pthread_t thread_id;
    int rc;

    // 初始化線程
    rc = pthread_create(&thread_id, NULL, my_thread_function, NULL);
    if (rc != 0) {
        perror("Failed to create thread");
        exit(EXIT_FAILURE);
    }

    // 在此處執行主線程的其他任務

    // 等待子線程完成
    pthread_join(thread_id, NULL);

    return 0;
}

在這個示例中,我們創建了一個名為my_thread_function的線程函數,然后在main()函數中使用pthread_create()初始化并運行這個線程。當pthread_create()成功執行時,它將返回0,并將新線程的ID存儲在thread_id變量中。

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