C:同时运行两个功能?

C:同时运行两个功能?,第1张

概述我在C中有两个函数: void function1(){ // do something}void function2(){ // do something while doing that} 我如何在同一时间运行这两个函数? 如果可能的话,请举例! 你会使用线程. 例如,pthreads是用于多线程的c库. 您可以查看此pthreads tutorial以获取更多详细信息 我在C中有两个函数:

voID function1(){    // do something}voID function2(){    // do something while doing that}

我如何在同一时间运行这两个函数?
如果可能的话,请举例!

解决方法 你会使用线程.

例如,pthreads是用于多线程的c库.

您可以查看此pthreads tutorial以获取更多详细信息.

以下是从this tutorial开始生成pthreads的程序示例.

#include <pthread.h>#include <stdio.h>#define NUM_THREADS     5voID *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:同时运行两个功能?全部内容,希望文章能够帮你解决C:同时运行两个功能?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1218959.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-05
下一篇2022-06-05

发表评论

登录后才能评论

评论列表(0条)

    保存