【C++】UBUNTU下多线程函数thread的使用

有两个函数t1和t2。创建多线程使两个函数同时运行,ubuntu系统代码如下

(1)thread为多线程函数库,应包含此头文件以调用thread

代码中thread th1(t1)
声明一个线程th1.内容为函数t1
该进程在创建后立即开始执行

(2)th1.join()
阻塞当前程序,避免程序执行完成导致退出
必须将线程join或者detach 等待子线程结束主进程才可以退出

若无此命令,会导致意外退出。如图
在这里插入图片描述
(3) 若编译时报错
在这里插入图片描述
因lpthread不是linux默认函数库
需要在g++编译时加入额外命令
g++ -o main.a main.cpp -lpthread

#include <iostream>
#include <thread>
#include <stdlib.h> //Sleep

#include <unistd.h>
// #include <windows.h>

using namespace std;

void t1() //普通的函数,用来执行线程
{
    cout << "t33331" << endl;
    // for (int i = 0; i < 10; ++i)
    while (true)
    {
        cout << "t1111" << endl;
        usleep(500 * 1000);
    }
}
void t2()
{
    while (1)
    {
        cout << "t22222\n";
        usleep(1000 * 1000);
    }
}
int main()
{

    thread th1(t1); //实例化一个线程对象th1,使用函数t1构造,然后该线程就开始执行了(t1())
    thread th2(t2);

    th1.join(); // 必须将线程join或者detach 等待子线程结束主进程才可以退出
    th2.join();

    // or use detach
    // th1.detach();
    // th2.detach();

    cout << "here is main\n\n";

    return 0;
}
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值