C:同时运行两个功能?

Dan*_*iel 4 c multithreading function

我在C中有两个函数:

void function1(){
    // do something
}

void function2(){
    // do something while doing that
}
Run Code Online (Sandbox Code Playgroud)

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

Ste*_*hen 9

你会使用线程.

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

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

这是一个从本教程产生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);
}
Run Code Online (Sandbox Code Playgroud)

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


GMa*_*ckG 5

这是不可能以标准方式做到的。您需要依赖一些第三方方法。即pthreadWin32 线程

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;
}
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

如果您想在两个平台上使用 POSIX,则有 POSIX 的 Windows 端口。