有两个函数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#include #include //Sleep #include // #include 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 << "t22222n"; 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 mainnn"; return 0; }



