溫馨提示×

linux c語言如何創建線程

小億
96
2024-12-07 10:27:37
欄目: 智能運維

在 Linux 中,使用 C 語言創建線程可以通過以下兩種方法實現:

  1. 使用 POSIX 線程庫(pthread)

首先,需要包含頭文件 pthread.h。然后,通過調用 pthread_create() 函數來創建線程。這是一個簡單的示例:

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

void *my_thread_function(void *arg) {
    printf("Hello from the new thread!\n");
    pthread_exit(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);
    }

    printf("Hello from the main thread!\n");

    // 等待線程結束
    pthread_join(thread_id, NULL);

    return 0;
}
  1. 使用系統調用 clone()

clone() 系統調用是 Linux 中創建線程的另一種方法。首先,需要包含頭文件 sys/types.hsys/wait.h。然后,通過調用 clone() 函數來創建線程。這是一個簡單的示例:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

int my_thread_function(void *arg) {
    printf("Hello from the new thread!\n");
    _exit(0);
}

int main() {
    pid_t pid = clone(my_thread_function, NULL, CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_THREAD | CLONE_SYSVSEM, NULL);
    if (pid < 0) {
        perror("Failed to create thread");
        exit(EXIT_FAILURE);
    }

    printf("Hello from the main thread!\n");

    // 等待線程結束
    waitpid(pid, NULL, 0);

    return 0;
}

這兩種方法都可以用于在 Linux 中使用 C 語言創建線程。POSIX 線程庫(pthread)是現代 Linux 系統中更常用的方法,因為它提供了更豐富的功能和更好的可移植性。

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