加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C:同时运行两个功能?

发布时间:2020-12-16 10:17:02 所属栏目:百科 来源:网络整理
导读:我在C中有两个函数: void function1(){ // do something}void function2(){ // do something while doing that} 我如何在同一时间运行这两个函数? 如果可能的话,请举例! 解决方法 你会使用线程. 例如,pthreads是用于多线程的c库. 您可以查看此pthreads tu
我在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     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 %ldn",t);
      rc = pthread_create(&threads[t],NULL,PrintHello,(void *)t);
      if (rc){
         printf("ERROR; return code from pthread_create() is %dn",rc);
         exit(-1);
      }
   }
   pthread_exit(NULL);
}

除了(你可能知道)“完全相同的时间”在技术上是不可能的.无论您是在单核或多核进程上运行,您都可以使用操作系统的调度程序来运行您的线程.不能保证它们会“同时”运行,而是可以分享单个核心.你可以启动两个线程并同时运行它们,但这可能不是你所追求的……

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读