C:同时运行两个功能? [英] C: Run two functions at the same time?

查看:90
本文介绍了C:同时运行两个功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C语言中有两个功能:

I have two functions in C:

void function1(){
    // do something
}

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

我该如何同时运行这两个功能? 如有可能,请提供示例!

How would I run these two functions at the exact same time? If possible, please provide an example!

推荐答案

您将使用线程.

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

For example, pthreads is a c library for multithreading.

您可以查看此 pthread教程以获得更多详细信息.

You can look at this pthreads tutorial for more details.

这是一个程序示例,该程序从本教程中产生pthread.

Here's an example of a program spawning pthreads from this tutorial.

#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);
}

除了(您可能知道的)在同一时间"在技术上是不可能的.无论您是在单核还是多核进程上运行,都必须依靠操作系统的调度程序来运行线程.无法保证它们将同时"运行,而是可以共享一个核心.您可以启动两个线程并发运行,但这可能不完全是您想要的...

Except that (as you probably know) "exact same time" isn't technically possible. Whether you're running on a single or multi-core process, you're at the mercy of the operating system's scheduler to run your threads. There is no guarantee that they will run "at the same time", instead they may time share a single core. You can start two threads and run them concurrently, but that may not be exactly what you're after...

这篇关于C:同时运行两个功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆