在fork()之后使用pthread_create()对两个整数求和
我正在处理一个小赋值,它使用一个简单的sum()函数在子进程和父进程中添加两个整数。包括必需的库 一个线程是在父进程中创建的,应该在创建后更改总和的值。创建线程似乎可行,但值不变 输出:在fork()之后使用pthread_create()对两个整数求和,c,linux,pthreads,fork,system-calls,C,Linux,Pthreads,Fork,System Calls,我正在处理一个小赋值,它使用一个简单的sum()函数在子进程和父进程中添加两个整数。包括必需的库 一个线程是在父进程中创建的,应该在创建后更改总和的值。创建线程似乎可行,但值不变 输出: Using a fork(), the value of z in the child process is: 30 Using a fork(), the value of z in the parent process is: 0 Using a thread, the value of z is: 0
Using a fork(), the value of z in the child process is: 30
Using a fork(), the value of z in the parent process is: 0
Using a thread, the value of z is: 0
代码:
intx,y,z,err;
无效*总和(){
z=y+x;
返回NULL;
}
int main(){
pid_t儿童;
pthread\u t线程;
//初始化变量
x=10,y=20,z=0;
child=fork();//子进程
如果(子级0){
//父母
printf(“等待子项完成…”\n);
等待(空);
printf(“使用fork(),父进程中的z值为:%d\n”,z);//fork进程后的z值不会更改
err=pthread_create(&thread,NULL,sum,NULL);
如果(err!=0){//create thread,等待它完成,然后打印z的值
printf(“主要功能:错误号为%d\n”,错误号);
出口(1);
}
否则{
printf(“使用线程,z的值为:%d\n”,z);//传递到线程后,z的值将更改
}
}
返回0;
}
使用fork(),子进程中的z值为:30
这是正确的
使用fork(),父进程中的z值为:0
未在父进程中计算z的值。因此,它被打印为0。父进程和子进程的地址空间不同。所以z在子进程中是30,但在父进程中是0
使用线程时,z的值为:0
主线程需要使用pthread_join等待sum线程结束,然后使用z的值。如果(err!=0){//create thread,等待它完成。
。实际上没有任何代码等待线程完成。调用pthread_join
。
int x, y, z, err;
void *sum(){
z=y+x;
return NULL;
}
int main(){
pid_t child;
pthread_t thread;
// Initializing variables
x=10, y=20, z=0;
child=fork(); // child process
if (child <0) // fork unsuccessful {
printf("fork unsuccessful");
exit(1); // check for creation error
}
if (child==0) { //child
sum(); // sum x and y and store it in z
printf("Using a fork(), the value of z in the child process is: %d\n", z);
}
if (child>0) {
// in parent
printf("waiting for child to complete....\n");
wait(NULL);
printf("Using a fork(), the value of z in the parent process is: %d\n", z); // value of z after the fork process won't change
err = pthread_create(&thread, NULL, sum, NULL);
if (err != 0) { // create thread, wait for it to complete, then print value of z
printf("main function: errno number is %d\n", errno);
exit(1);
}
else {
printf("Using a thread, the value of z is: %d\n", z); //value of z after passing to the thread will change
}
}
return 0;
}