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

问题描述:

我目前有一个程序,该程序可以产生任意数量的子进程,并且我对使它实现线程而不是进程感兴趣.我在理解如何从现有资源转换时遇到麻烦,这是使用流程的代码:

I currently have this program which spawns an arbitrary number of child processes and I'm interested in having it implement threads instead of processes. I'm having trouble understanding how to convert from what I have, here is the code which uses processes:

#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实际编写它

Is it as simple as changing a few lines to make it use threads instead? I understand the theory behind using threads but not how to actually write it in C given what I have here

一般情况取决于线程是否彼此完全独立.如果您使用多线程,则必须确保对任何共享资源都进行了适当的保护.

The general case depends on whether the threads are wholly independent of each other. If you go multi-threaded, you must ensure that any shared resource is accessed appropriate protection.

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

The code shown has a shared resource in the use of srand() and rand(). You will get different results in a multi-threaded process compared with those from multiple separate processes. Does this matter? If not, you may be able to let the threads run, but the C standard says the srand() and rand() functions don't have to be thread-safe.

如果很重要(可能确实如此),则需要使用其他PRNG(伪随机数生成器),该PRNG允许您使用独立的序列(例如POSIX

If it matters — and it probably does — you need to use a different PRNG (pseudo-random number generator) which allows you to have independent sequences (for example, POSIX nrand48() — there may well be better alternatives, especially if you use modern C++).

使用getpid()在多线程进程中也不能很好地工作.每个线程将获得相同的值(因为这些线程都是同一进程的一部分),因此,由于其他原因,这些线程将不会获得独立的随机数序列.

The use of getpid() won't work well in a multi-threaded process either. Each thread will get the same value (because the threads are all part of the same process), so the threads won't get independent sequences of random numbers for another reason.