【问题标题】:Thread to process要处理的线程
【发布时间】:2016-08-21 14:50:25
【问题描述】:

如何重写这段代码以使用进程而不是线程?我尝试学习 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;
}

感谢大家的帮助

【问题讨论】:

  • 您可以使用任何形式的IPC 来实现消息传递,这是一个好的开始。您可以使用套接字或命名/匿名管道等来执行此操作。阅读链接以开始使用 (;
  • 你可以重构你的代码并使用fork一个子进程和一个管道来发送/接收数据。请记住,您需要在子进程工作时将父进程保持在某种循环中。

标签: c multithreading process


【解决方案1】:

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

然后,父进程将在本地继续使用您的pthread_create()s 之后的内容。

然后孩子会调用传入的方法。

新创建的进程的pid将扮演tid的角色。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-25
    • 2013-04-29
    • 2017-04-12
    • 1970-01-01
    • 2017-01-23
    相关资源
    最近更新 更多