温馨提示×

c语言怎么让两个函数并行

小亿
139
2024-02-22 17:02:31
栏目: 编程语言

在C语言中,可以使用多线程来让两个函数并行执行。可以使用pthread库来创建线程并让两个函数在不同的线程中执行。

以下是一个示例代码,其中使用pthread库创建两个线程并让两个函数并行执行:

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

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

void* func2(void* arg) {
    for (int i = 0; i < 10; 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;
}

在上面的代码中,我们定义了两个函数func1和func2,并在main函数中使用pthread_create函数创建两个线程来执行这两个函数。最后使用pthread_join函数等待两个线程执行完毕并回收资源。

通过使用多线程,我们可以让两个函数并行执行,从而提高程序的性能和效率。

0