多线程学习(一)

版权声明:博主瞎写,随便看看 https://blog.csdn.net/LAN74__/article/details/78867423

多线程在C++中占有很重要的一部分,也是很重要的一部分

fork函数

#include <iostream>
#include <unistd.h>
using namespace std;
int main(){
    pid_t pid;
    int num = 10;
    for(int i = 1;i <= 3;i++)
        cout << "befor i = " << i << endl;
    pid = fork();
    if(pid > 0){
        cout << "This is fater,pid = " << getpid() << endl;
        num++;
    }
    else if(pid == 0){
        cout << "This is son ,pid = " << getpid() << "  father id : "<< getppid() << endl;
        num++;
    }
    for(int i = 1; i <= 3; i++)
        cout << "end i = " << i << endl; 
    cout << "!!!!!!!" << "    " << num << endl;
}

fork()函数,分叉函数,生成一个和父进程一模一样的子进程,同时,这个函数有两个返回值,一个子函数的,一个父函数的。

fork()函数的两个头文件

#include<unistd.h>
#include<sys/types.h>

fork()函数的返回值是pid_t类型的,而且我们可以通过其值大小来分辨进程,父进程的返回值是其子进程的进程ID,子进程则为0。
同时,getpid():获取当前进程的ID,getppid()获取父进程的进程的ID。
每个进程都有自己对应的ID,我们在Linux下的终端就可以通过 ps aux这条指令来查询当前所有进程

#include <iostream>
#include <unistd.h>
using namespace std;
int main(){
    pid_t pid;
    int num = 100;
    int i;
    for(i = 1; i<=5;i++){
        pid = fork();
        if(pid == 0)
            break;
    }
    if(i == 1)
        cout << "This is first son id :" << getpid()  << endl;
    if(i == 6)
        cout << "This is father id :" << getpid() << endl;

}

同时,看这个例子,我们可以通过多次循环,由一个父进程得到多个并列的子进程,但是在循环的时候要注意一点,如果直接用循环来fork的话,就像我们最初的遇到的一个兔子生小兔子,小兔子第二年就可以生兔子。我们这个循环就要做一个判断,当它的进程ID判断出来为0后,我们就把他掐断( 这样就可以生出来许多并列的子进程了,当然,父进程都要是最后才会终止的

猜你喜欢

转载自blog.csdn.net/LAN74__/article/details/78867423