C:同时运行两个功能?

时间:2010-06-16 05:54:49

标签: c multithreading function

我在C中有两个函数:

void function1(){
    // do something
}

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

我如何在同一时间运行这两个功能? 如果可能,请提供一个示例!

3 个答案:

答案 0 :(得分:9)

你会使用线程。

例如,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 %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);
}

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

答案 1 :(得分:3)

不可能以标准方式进行。您需要依赖某些第三方方法。即,pthreadsWin32 threads

POSIX示例:

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

void* print_once(void* pString)
{
    printf("%s", (char*)pString);

    return 0;
}

void* print_twice(void* pString)
{
    printf("%s", (char*)pString);
    printf("%s", (char*)pString);

    return 0;
}

int main(void)
{
    pthread_t thread1, thread2;

    // make threads
    pthread_create(&thread1, NULL, print_once, "Foo");
    pthread_create(&thread2, NULL, print_twice, "Bar");

    // wait for them to finish
    pthread_join(thread1, NULL);
    pthread_join(thread2, NULL); 

    return 0;
}

Win32示例:

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>

DWORD print_once(LPVOID pString)
{
    printf("%s", (char*)pString);

    return 0;
}

DWORD print_twice(LPVOID pString)
{
    printf("%s", (char*)pString);
    printf("%s", (char*)pString);

    return 0;
}

int main(void)
{
    HANDLE thread1, thread2;

    // make threads
    thread1 = CreateThread(NULL, 0, print_once, "Foo", 0, NULL);
    thread2 = CreateThread(NULL, 0, print_once, "Bar", 0, NULL);

    // wait for them to finish
    WaitForSingleObject(thread1, INFINITE);
    WaitForSingleObject(thread2, INFINITE);

    return 0;
}

如果您想在两个平台上使用它,可以使用POSIX的Windows端口。

答案 2 :(得分:1)

对于'同时'的近似值,您可以在自己的线程中执行每个函数(有关详细信息,请参阅https://computing.llnl.gov/tutorials/pthreads/

如果您需要确保这两个函数以某种同步方式执行操作,您将需要了解同步原语,如互斥,信号量和监视器。