1 c++多线程创建和传参

什么是进程?

系统资源分配的最小单位。

什么是线程?

操作系统调度的最小单位,即程序执行的最小单位。

为什么需要多线程?

(1)加快程序执行速度和响应速度, 使得程序充分利用CPU资源。

(2)多个线程可以在同一时间并行执行,将一个任务分成多份,让多个线程执行,加快执行速度。比如for循环,可以分解成多个线程同时处理。

(3)相比进程,线程创建和销毁的成本更低.

(4)同一进程内线程间的切换比进程间的切换要快,尤其是用户级线程间的切换。

进程和线程之间的关系

(1)线程属于进程,一个进程可以拥有多个线程,每个线程执行不同的任务。

(2)每个进程都有一个主线程。

(3)一个进程中的所有线程,共享资源和进程空间(代码段、数据段、堆等),但每个线程有各自的栈空间和线程控制块。

(4)进程之间的资源是独立的。

(5)进程间切换时,需要交换整个地址空间,而线程之间切换时,只是切换线程的上下文环境。

线程的状态

 线程的状态反映了线程在其生命周期中的不同阶段

  • New(新创建)

        线程已被创建,但未开始执行。

  • Ready(就绪)或 Runnable(可运行)

        线程已经准备好运行,但未获得CPU资源,进入就绪队列,就等着运行了。

  • Running(运行)

        线程正在cpu上执行代码,就绪状态的线程获取了CPU资源。

  • Blocked(阻塞)或 Waiting(等待)

        条件不满足,进入阻塞状态,条件满足了进入就绪状态。线程因为某种原因(如等待I/O操作完成、等待获取锁、等待通知等)而暂停执行。线程不会消耗CPU资源,并且不能执行任何代码,直到阻塞的原因被消除(如I/O操作完成、锁被释放、收到通知等)。

  • Terminated(被终止)

        线程已经完成了任务,或者由于某种原因(如异常,返回)而退出。一旦线程终止,就不能再运行。

sleep: 等到睡眠时间到,会自动恢复到就绪态。

挂起:是把进程或线程挂在外存,需要执行时,再把它移到内存中。

阻塞: 在等待某种事件或者资源,一旦获得资源或者事件信息就自动转成就绪态。

线程创建和参数传递

值传递

#include<thread>
#include<iostream>
#include<vector>

using namespace std;

// 值传递
// 该函数复制传入的变量,即在子线程中修改该参数不会影响主线程的参数。
void (int num)
{
    num += 1;

    cout << "子线程id: " << this_thread::get_id()<< ", num: " << num<< endl;
    cout<<"child thread num memory address: "<< &num<<endl;
}

int main(int argc, char* argv[]){
    int num = 10;
    
    //t1为新建
    //第一个参数为函数名,第二个参数为该函数的第一个参数,如果该函数有多个参数就依次写在后面。此时线程开始执行。
    thread t1(thread_func_1, num);
    std::this_thread::sleep_for(std::chrono::milliseconds(100)); //sleep 100ms

    cout << "主线程id: " << this_thread::get_id() << endl;
    cout << "主线程中获取子线程id " << t1.get_id() << endl;
    cout<<"main thread num memory address: "<< &num<<", num = "<<num<<endl;

    t1.join(); //阻塞主线程, 直至子线程执行结束。


    return 0;
}

编译

 g++ main.cpp -o main -l pthread

运行

./main

执行结果如下:

子线程id: 140038849767168, num: 11
child thread num memory address: 0x7f5d55e51dac
主线程id: 140038867724096
主线程中获取子线程id 140038849767168
main thread num memory address: 0x7fffeef939d0, num = 10

子线程num=11, nun内存地址是0x7f5d55e51dac;主线程num=10, nun内存地址是 0x7fffeef939d0。说明子线程中修改参数的值,没有改变主线程中的值。 num被复制后传递到thread_func_1中。

引用传递

#include<thread>
#include<iostream>
#include<vector>

using namespace std;

//传递引用
//传递参数时,使用std::ref, 在子线程中修改该参数会影响主线程的参数。
void thread_func_1(int& num)
{
    num += 1;
    
    cout << "thread_func_1子线程id: " << this_thread::get_id()<< ", num: " << num<< endl;
    cout<<"child thread num memory address: "<< &num<<endl;
}

int main(int argc, char* argv[]){
    int num = 10;
    thread t1(thread_func_1, std::ref(num));

    std::this_thread::sleep_for(std::chrono::milliseconds(100)); //sleep 100ms

    cout << "主线程id: " << this_thread::get_id() << endl;
    cout << "主线程中获取子线程id " << t1.get_id() << endl;
    cout<< "main thread num memory address: "<< &num<<", num = "<<num<<endl;

    t1.join(); //阻塞主线程, 直至子线程执行结束。


    return 0;
}




编译

 g++ main.cpp -o main -l pthread

运行

./main

执行结果如下:

thread_func_1子线程id: 140508139726592, num: 11
child thread num memory address: 0x7fffa22eea90
主线程id: 140508157683520
主线程中获取子线程id 140508139726592
main thread num memory address: 0x7fffa22eea90, num = 11

子线程num=11, 主线程num=11,内存地址都是0x7fffa22eea90。说明子线程中修改参数num的值,主线程中num数值也改变了。创建线程传参时加上std::ref操作的才是同一块内存。

指针传递



#include<thread>
#include<iostream>
#include<vector>

using namespace std;

// 传递指针, 在子线程中修改该参数会影响主线程的参数。
void thread_func_1(int* p)
{
    *p = *p + 1;
    cout << "子线程id: " << this_thread::get_id() <<endl;
    cout<<"child thread num memory address: "<< p<< ", num = " << *p<<endl;
}

int main(int argc, char* argv[]){
    int num = 10;
    thread t1(thread_func_1, &num);

    std::this_thread::sleep_for(std::chrono::milliseconds(100)); //sleep 100ms

    cout << "主线程id: " << this_thread::get_id() << endl;
    cout<<"main thread num memory address: "<< &num<<", num = "<<num<<endl;

    t1.join(); //阻塞主线程, 直至子线程执行结束。


    return 0;
}




编译

 g++ main.cpp -o main -l pthread

运行

./main

执行结果如下:

 

子线程id: 140096623552256
child thread num memory address: 0x7ffed5c7ead0, num = 11
主线程id: 140096641509184
main thread num memory address: 0x7ffed5c7ead0, num = 11

子线程num=11, 主线程num=11,内存地址相同。说明子线程中修改参数num的值,主线程中num数值也改变了。子线程和主线程访问的是同一块内存,传递指针和引用效果是一样的。

 线程可调用对象

C++中可调用对象:函数指针、lambda表达式、bind对象、仿函数等

函数指针

上面介绍传递引用代码中,介绍的可调用对象thread_func_1是函数指针。

#include<thread>
#include<iostream>
#include<vector>

using namespace std;

// 值传递
// 该函数复制传入的变量,即在子线程中修改该参数不会影响主线程的参数。
void (int num)
{
    num += 1;

    cout << "子线程id: " << this_thread::get_id()<< endl;
    cout<<"child thread num memory address: "<< &num<< ", num = " << num<<endl;
}

int main(int argc, char* argv[]){
    int num = 10;

    thread t1(thread_func_1, num);

    std::this_thread::sleep_for(std::chrono::milliseconds(100)); //sleep 100ms

    cout << "主线程id: " << this_thread::get_id() << endl;
    cout<<"main thread num memory address: "<< &num<<", num = "<<num<<endl;

    t1.join(); //阻塞主线程, 直至子线程执行结束。


    return 0;
}

bind对象

#include<thread>
#include<iostream>
#include<vector>
#include <functional>

using namespace std;

void thread_function(int arg1, std::string arg2) {
    std::cout << "child thread bind arguments: " << arg1 << " " << arg2 << std::endl;
}
                                                                                                                            
int main(int argc, char* argv[]){
    // std::bind将函数与其参数一起进行绑定
    // std::placeholders::_1 参数占位符, 指定函数参数的位置
    auto fn = std::bind(thread_function, std::placeholders::_1, std::placeholders::_2);
    std::thread t2(fn, 1, "20");
    t2.join();

    return 0;
}

编译

 g++ main.cpp -o main -l pthread

运行

./main

执行结果如下:

child thread bind arguments: 1 20

Lambda表达式

#include<thread>
#include<iostream>
#include<vector>

using namespace std;


void thread_func_1(int arg1, int arg2){
    std::cout << "child thread arguments: " << arg1 << ", " << arg2 << std::endl;
}

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

    int arg1 = 3;
    int arg2 = 5;

    //lambda表达式
    std::thread t1([arg1, arg2](){
        thread_func_1(arg1, arg2);
    });

    t1.join();
    

    return 0;
}

输出结果: 

child thread arguments: 3, 5

 仿函数

#include<thread>
#include<iostream>
#include<vector>

using namespace std;


class MyClass{
    public:
        MyClass(){cout << "constructor" << endl;}
        void operator()(int num)   // 重载括号运算符
        {
            cout << "num " << num << endl;
        }

};

int main(int argc, char* argv[]){
    MyClass object;
    std::thread t1(object, 5);
    t1.join();

    return 0;
}

成员函数

#include<thread>
#include<iostream>
#include<vector>

using namespace std;


class MyClass{
    public:
        void test(){
            cout<<"member function"<<endl;
        }

};



int main(int argc, char* argv[]){
    MyClass object;
    //第一个参数为类成员函数,第二个为类对象
    std::thread t1(&MyClass::test, &object);

    if(t1.joinable()){
        t1.join();
    }

    return 0;
}

  • 28
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值