将基于进程的程序转换为基于线程的版本?

Convert a process based program into a thread based version?

我目前有这个程序生成任意数量的子进程,我有兴趣让它实现线程而不是进程。我无法理解如何从我所拥有的进行转换,这里是使用进程的代码:

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>

void childprocess(int num);

int main(int argc, char **argv) {

  if (argc != 2)
  {
    fprintf(stderr, "Usage: %s num-procs\n", argv[0]);
    exit(EXIT_FAILURE);
  }

  int counter;
  pid_t pid = getpid();
  int x = atoi(argv[1]);

  printf("Parent Process, my PID is %d\n", pid);

  for(counter = 1; counter <= x; counter++){

    if(!fork()){
      printf("Child %d is born, my PID is %d\n", counter, getpid());
      childprocess(counter);
      printf("Child %d dies\n", counter);
      exit(0);
    }
  }
}

void childprocess(int num){

  srand(getpid());
  int max = rand() % 100;

  for(int i = 0; i < max; i++){
    printf("Child %d executes iteration: %d\n", num, i);
  }

}

是不是改几行就改用线程这么简单?我理解使用线程背后的理论,但不知道如何在 C 中实际编写它,因为我在这里

一般情况取决于线程是否完全相互独立。如果您使用多线程,则必须确保访问任何共享资源都受到适当的保护。

显示的代码在 srand()rand() 的使用中具有共享资源。与来自多个独立进程的结果相比,您将在多线程进程中获得不同的结果。这有关系吗?如果不是,您可以让线程 运行,但 C 标准规定 srand() and rand() 函数不必是线程安全的。

如果它很重要——而且它可能很重要——你需要使用不同的 PRNG(伪随机数生成器),它允许你有独立的序列(例如,POSIX nrand48() —可能会有更好的选择,尤其是如果您使用现代 C++)。

getpid() 的使用在多线程进程中也不会很好地工作。每个线程都会得到相同的值(因为线程都是同一个进程的一部分),所以线程不会因为另一个原因得到独立的随机数序列。