gpt4 book ai didi

C:同时运行两个函数?

转载 作者:太空狗 更新时间:2023-10-29 15:14:31 25 4
gpt4 key购买 nike

我在 C 中有两个函数:

void function1(){
// do something
}

void function2(){
// do something while doing that
}

如何同时运行这两个函数?如果可能,请提供示例!

最佳答案

您将使用线程。

例如,pthreads 是一个用于多线程的 c 库。

可以看看这个pthreads tutorial更多细节。

这是一个从 this tutorial 生成 pthread 的程序示例.

#include <pthread.h>
#include <stdio.h>
#define NUM_THREADS 5

void *PrintHello(void *threadid)
{
long tid;
tid = (long)threadid;
printf("Hello World! It's me, thread #%ld!\n", tid);
pthread_exit(NULL);
}

int main (int argc, char *argv[])
{
pthread_t threads[NUM_THREADS];
int rc;
long t;
for(t=0; t<NUM_THREADS; t++){
printf("In main: creating thread %ld\n", t);
rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
if (rc){
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
pthread_exit(NULL);
}

除了(您可能知道)“完全相同的时间”在技术上是不可能的。无论您是在单核还是多核进程上运行,您都受制于操作系统的调度程序来运行您的线程。不能保证它们会“同时”运行,相反它们可能会共享一个内核。您可以启动两个线程并同时运行它们,但这可能不是您想要的...

关于C:同时运行两个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3051009/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com