溫馨提示×

c語言如何讓兩個(gè)函數(shù)并行執(zhí)行

小億
192
2024-05-21 18:03:31
欄目: 編程語言

在C語言中,可以使用多線程來實(shí)現(xiàn)兩個(gè)函數(shù)的并行執(zhí)行。在使用多線程之前,需要包含頭文件<pthread.h>,并使用pthread_create()函數(shù)創(chuàng)建新的線程。以下是一個(gè)簡單的示例代碼:

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

void* func1(void* arg) {
    for (int i = 0; i < 5; i++) {
        printf("Function 1: %d\n", i);
    }
    return NULL;
}

void* func2(void* arg) {
    for (int i = 0; i < 5; i++) {
        printf("Function 2: %d\n", i);
    }
    return NULL;
}

int main() {
    pthread_t thread1, thread2;

    pthread_create(&thread1, NULL, func1, NULL);
    pthread_create(&thread2, NULL, func2, NULL);

    pthread_join(thread1, NULL);
    pthread_join(thread2, NULL);

    return 0;
}

在上面的代碼中,我們定義了兩個(gè)函數(shù)func1func2,分別用來執(zhí)行不同的任務(wù)。在main函數(shù)中,我們使用pthread_create()函數(shù)創(chuàng)建了兩個(gè)新線程,分別執(zhí)行func1func2函數(shù)。最后,使用pthread_join()函數(shù)等待兩個(gè)線程執(zhí)行完畢。

需要注意的是,多線程的使用需要注意線程之間的同步和互斥,以避免出現(xiàn)競爭條件和死鎖等問題。

0