Zam-Oxy
Zam-Oxy

Reputation: 130

Convert Pthread to process fork()

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

Upvotes: 2

Views: 238

Answers (1)

CRM
CRM

Reputation: 4635

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.

Upvotes: 1

Related Questions