问题
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);
}
}
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
回答1:
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.
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.
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++).
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.
来源:https://stackoverflow.com/questions/58826841/convert-a-process-based-program-into-a-thread-based-version