要处理的线程

Thread to process

如何重写此代码以使用进程而不是线程?我尝试学习C语言的过程编程。我不知道我该怎么做。此代码使用线程。有关此算法的更多信息,请参见第 153 - 158 页:

http://www.greenteapress.com/semaphores/downey08semaphores.pdf

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

#define MAX_PASSENGERS 500

sem_t loading, loaded, unloading, unloaded;

int n, c;

void *passenger (void *tid) {
  int i = *((int*) tid);

  while (1) {

    sem_wait(&loading);
    printf("pass(i=%d).board()\n", i);
    sem_post(&loaded);

    sem_wait(&unloading);
    printf("pass(i=%d).unboard()\n", i);
    sem_post(&unloaded);

  }
}

void *roller_coaster () {
  while (1) {

    printf("car.load(c=%d)\n", c);
    for (int i = 0; i < c; i++) {
      sem_post(&loading);
    }

    // wait for c passengers to load
    for (int i = 0; i < c; i++) {
      sem_wait(&loaded);
    }

    printf("car.run()\n");

    sleep(1);

    printf("car.unload(c=%d)\n", c);
    for (int i = 0; i < c; i++) {
      sem_post(&unloading);
    }

    // wait for c passengers to unload
    for (int i = 0; i < c; i++) {
      sem_wait(&unloaded);
    }

  }
}

int main () {

  printf("Number of passengers(n, n <= 500): ");
  scanf("%d", &n);
  printf("Number of passengers per cart(c, c < n): ");
  scanf("%d", &c);

  sem_init(&loading, 0, 0);
  sem_init(&unloading, 0, 0);

  sem_init(&loaded, 0, 0);
  sem_init(&unloaded, 0, 0);

  pthread_t car;
  pthread_t tid[MAX_PASSENGERS];

  int my_ids[MAX_PASSENGERS];

  pthread_create(&car, NULL, roller_coaster, NULL);

  for (int i = 0; i < n; i++) {
    my_ids[i] = i;
    pthread_create(&tid[i], NULL, passenger, &my_ids[i]);
  }

  pthread_join(car, NULL);

  return 0;
}

感谢大家的帮助

要使用进程而不是线程,您需要将 pthread_create() 调用替换为使用 fork().

的方法

然后 parent 过程将在您的 pthread_create() 之后在本地继续。

然后 child 将调用传入的方法。

新创建的进程pid将取代tid

因为您似乎已经在使用 posix 信号量,所以这将继续有效。但是,您将需要使用命名信号量(参见 sem_open)并在 child 进程中(在调用您的方法之前)也使用它来在进程之间共享信号量。