C: Perform two functions simultaneously?

I have two functions in C:

function1(){
// do something
}

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

How will I launch these two at the same time? If possible, give an example!

+3
source share
3 answers

You must use streams.

For example, pthreads is a c-library for multithreading.

You can see this pthreads tutorial for more details.

Here is an example program in which pwnreads is 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 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);
}

, ( , , ), " " . , , . , "", . , , ...

+8

. . , pthreads Win32.

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

Windows POSIX, .

+3

In the approximation of "at the same time" you can perform each function in your thread (see https://computing.llnl.gov/tutorials/pthreads/ for more information)

If you need to ensure that these two functions perform operations in a somehow synchronized way, you need to learn about synchronization primitives such as mutexes, semaphores, and monitors.

+1
source

Source: https://habr.com/ru/post/1750231/


All Articles