C语言如何让两个函数同时执行
时间: 2023-12-29 12:06:09 浏览: 69
在C语言中,两个函数可以通过多线程的方式同时执行。你可以使用C语言中的线程库来创建和管理线程,让两个函数在不同的线程中执行。具体来说,你可以使用pthread库来创建和管理线程。下面是一个简单的示例代码,其中两个函数分别在不同的线程中执行:
```
#include <pthread.h>
#include <stdio.h>
void* function1(void* arg)
{
printf("Function 1 is running.\n");
return NULL;
}
void* function2(void* arg)
{
printf("Function 2 is running.\n");
return NULL;
}
int main()
{
pthread_t thread1, thread2;
// 创建两个线程,分别执行 function1 和 function2 函数
pthread_create(&thread1, NULL, function1, NULL);
pthread_create(&thread2, NULL, function2, NULL);
// 等待两个线程执行完毕
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
return 0;
}
```
在上面的代码中,我们使用pthread_create函数创建了两个线程,分别执行function1和function2函数。然后,我们使用pthread_join函数等待两个线程执行完毕。这样,就可以让两个函数同时执行了。