因为需要,学了一下《C++并行编程实战》,总结一个Linux下 C++最简易多线程程序。
基础部分就是最简易多线程程序写法,后面是自己实验。
实验结论为:如下分线程可以达到多个函数同时进行的目的,运行程序为多核工作。
基础部分
CmakeList:
cmake_minimum_required(VERSION 2.6)
set( CMAKE_CXX_FLAGS "-std=c++11 -O3" )
project(test004)
add_executable(test004 main.cpp)
install(TARGETS test004 RUNTIME DESTINATION bin)
TARGET_LINK_LIBRARIES(test004 pthread)
第二行和最后一行是必要的,thread库需要C++11标准,同时你得引用一下库。
主函数:
#include <iostream>
#include <thread>
using namespace std;
void hello()
{
cout<<"hello"<<endl;
}
int main(int argc, char **argv)
{
thread t(hello);
t.join();
return 0;
}
个人实验
one
程序是两个相同没啥用但耗时间的子函数被分线程调用的程序。
#include <iostream>
#include <thread>
#include <time.h>
clock_t start1, start2,end1,end2;
void test_one()
{
int i,j=0;
for (i=0;i<1000000;i++)
{
j=(j+int(i/3))%10;
}
std::cout<<"test_one:"<<j<<std::endl;
}
void test_two()
{
int i,j=0;
for (i=0;i<1000000;i++)
{
j=(j+int(i/3))%10;
}
std::cout<<"test_two:"<<j<<std::endl;
}
int main(int argc, char **argv) {
start1 = clock();
std::thread t(test_two);
start2 = clock();
test_one();
end1 = clock();
t.join();
end2 = clock();
std::cout<<"start_time:"<<(start2-start1)<<std::endl;
std::cout<<"time:"<<(end1-start2)<<std::endl;
std::cout<<"end_time:"<<(end2-end1)<<std::endl;
return 0;
}
它的输出一般为:
Starting: /media/eminbogen/Eminbogen001/Temp/C++/test/test004/test004/build/test004
test_two:7
test_one:7
start_time:98
time:12408
end_time:14
*** Exited normally ***
说明两个函数完成时间相同。
two
在子函数的循环中加了两句话if((i%10000)==0) std::cout<<"test_two"<<std::endl;方便我们看是否同时处理两个子函数。
void test_one()
{
int i,j=0;
for (i=0;i<1000000;i++)
{
j=(j+int(i/3))%10;
if((i%10000)==0) std::cout<<"test_one"<<std::endl;
}
std::cout<<"test_one:"<<j<<std::endl;
}
void test_two()
{
int i,j=0;
for (i=0;i<1000000;i++)
{
j=(j+int(i/3))%10;
if((i%10000)==0) std::cout<<"test_two"<<std::endl;
}
std::cout<<"test_two:"<<j<<std::endl;
}
输出为
test_one
test_two
test_one
test_two
test_one
test_two
test_one
test_two
......
test_one
test_two
test_one
test_two
test_one:7
test_two
test_two:7
start_time:83
time:13230
end_time:1911
*** Exited normally ***
说明确实是在同时处理两个函数,虽然最后有点误差。同时,在把(i%10000)改为(i%1000)后发现,test_one,test_two产生并不是均匀的。
three
然后我尝试先后处理两个子函数
#include <iostream>
#include <thread>
#include <time.h>
clock_t start1, start2,end1,end2;
void test_one()
{
int i,j=0;
for (i=0;i<1000000;i++)
{
j=(j+int(i/3))%10;
}
std::cout<<"test_one:"<<j<<std::endl;
}
void test_two()
{
int i,j=0;
for (i=0;i<1000000;i++)
{
j=(j+int(i/3))%10;
}
std::cout<<"test_two:"<<j<<std::endl;
}
int main(int argc, char **argv) {
start1 = clock();
test_one();
end1 = clock();
test_two();
end2 = clock();
std::cout<<"one_time:"<<(end1-start1)<<std::endl;
std::cout<<"two_time:"<<(end2- end1 )<<std::endl;
return 0;
}
输出
Starting: /media/eminbogen/Eminbogen001/Temp/C++/test/test004/test004/build/test004
test_one:7
test_two:7
one_time:7048
two_time:6314
*** Exited normally ***
说明总时间没有改变。
four
思考没有减少时间的原因,或许我的程序运算量小不够引起并行处理,或许是多核处理需要别的语句。
于是我成倍的增加计算数据量,并观察CPU运行情况,最后发现,成倍运算数据下,时间成倍增加,各CPU增加使用比,满使用比后增加时间,说明程序运行就是多核同处理的。