C++11 多线程编程
简单多线程编程例子
关键字:
thread:建立一个线程,thread name(thread_func)
join: 加入线程队列,name.join()
#include <iostream>
#include <thread>
#include <Windows.h>
using namespace std;
void thread01(){
for(int i=0;i<5;i++){
std::cout<<"Thread 01 is working"<<std::endl;
Sleep(100);
}
}
void thread02(){
for(int i=0;i<5;i++){
std::cout<<"Thread 02 is working"<<std::endl;
Sleep(200);
}
}
int int main(int argc, char const *argv[])
{
thread task01(thread01);
thread task02(thread02);
task01.join();
task02.join();
for(int i=0;i<5;i++){
std::cout<<"main thread is working"<<std::endl;
}
return 0;
}子线程剥离主线程
两个子线程并行执行,join函数会阻塞主流程,所以子线程都执行完成之后才继续执行主线程。可以使用detach将子线程从主流程中分离,独立运行,不会阻塞主线程
#include <iostream>
#include <thread>
#include <Windows.h>
using namespace std;
void thread01(){
for(int i=0;i<5;i++){
std::cout<<"Thread 01 is working"<<std::endl;
Sleep(100);
}
}
void thread02(){
for(int i=0;i<5;i++){
std::cout<<"Thread 02 is working"<<std::endl;
Sleep(200);
}
}
int int main(int argc, char const *argv[])
{
thread task01(thread01);
thread task02(thread02);
task01.detach();
task02.detach();
for(int i=0;i<5;i++){
std::cout<<"main thread is working"<<std::endl;
}
return 0;
}带参子线程
在绑定的时候也可以传入参数
#include <iostream>
#include <thread>
#include <Windows.h>
using namespace std;
void thread01(int num){
for(int i=0;i<num;i++){
std::cout<<"Thread 01 is working"<<std::endl;
Sleep(100);
}
}
void thread02(int num){
for(int i=0;i<num;i++){
std::cout<<"Thread 02 is working"<<std::endl;
Sleep(200);
}
}
int int main(int argc, char const *argv[])
{
thread task01(thread01,5);
thread task02(thread02),5;
task01.detach();
task02.detach();
for(int i=0;i<5;i++){
std::cout<<"main thread is working"<<std::endl;
}
return 0;
}mutex并行
#include <iostream>
#include <thread>
#include <Windows.h>
#include <mutex>
mutex mu;
int totalNum = 100;
void thread01(){
while(totalNum>0){
mu.lock();
std::cout<<totalNum<<std::endl;
totalNum--;
Sleep(100);
mu.unlock();
}
}
void thread02(){
whiel(totalNum>0){
mu.lock();
std::cout<<totalNum<<std::endl;
totalNum--;
Sleep(100);
mu.unlock();
}
}
int int main(int argc, char const *argv[])
{
thread task01(thread01);
thread task02(thread02);
task01.detach();
task02.detach();
return 0;
}
本文介绍C++11中多线程的基本用法,包括线程创建、join与detach操作、带参数线程及互斥锁的使用等,并通过具体代码示例进行说明。
6582

被折叠的 条评论
为什么被折叠?



