2

With this basic pthread code below, what is the method to convert pthread_create to fork() and achieve a similar outcome.

#include <stdio.h>
#include <pthread.h>
#include <semaphore.h> 
#include <unistd.h>
sem_t mutex; 
void* wait_t(void* a)
{
    (int)a--;
    if ((int)a < 0)
    {
        sem_wait(&mutex);
        printf("waiting\n");
    }
}
void* signal_t(void* a)
{
    (int)a++;
    if ((int)a <= 0)
    {
        printf("signal\n");
        sem_post(&mutex);
    }
}
int main()
{
    sem_init(&mutex, 0, 1);
    int i = -2;
    pthread_t t1, t2; 
    pthread_create(&t1, NULL, wait_t, i);
    pthread_create(&t2, NULL, signal_t, i); 
    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    exit(0); 
}
Zam-Oxy
  • 130
  • 10
  • Possible duplicate of https://stackoverflow.com/questions/10909011/how-to-use-fork-to-create-only-2-child-processes – peachykeen May 03 '20 at 13:58
  • You have to create two child processes with `fork()` and in each child process you invoke the functions `wait_t`and `signal_t`. – CRM May 03 '20 at 13:59
  • @peachykeen that question is about how to use `fork()` this question convert pthread to process and achieve a similar outcome – Zam-Oxy May 03 '20 at 14:01

1 Answers1

1

Unless I'm missing something, the following code allows you to achieve the same functionality using processes instead of threads.

#include <stdio.h>
#include <semaphore.h> 
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>

sem_t mutex; 
void wait_t(int a)
{
    a--;
    if (a < 0)
    {
        sem_wait(&mutex);
        printf("waiting\n");
    }
}

void signal_t(int a)
{
    a++;
    if (a <= 0)
    {
        printf("signal\n");
        sem_post(&mutex);
    }
}

int main()
{
    sem_init(&mutex, 0, 1);
    int i = -2;

    if(fork() == 0){ // create 1st child process
        wait_t(i);
        exit(0);
    }

    if(fork() == 0){ // create 2nd child process
        signal_t(i);
        exit(0);
    }


    wait(NULL);
    wait(NULL);

    exit(0); 
}

Note: I'm not validating any possible errors thrown by fork() as it is advisable to do.

CRM
  • 4,569
  • 4
  • 27
  • 33
  • Why not use `pid_t` to label each process. – Zam-Oxy May 07 '20 at 04:22
  • You can use it if you want, but in your original example you were not using this information so I didn't use it in the answer. You can get the PID for each process using `getpid()`, and the parent of each process can get this value via `fork()` which, in case of success, returns the PID of the just created child process. – CRM May 07 '20 at 07:57