以下内容就是参照以上博主的博客:
头文件:#include<iostream>
#include <thread>
#include <mutex>
一、无参函数
//无参函数
void hello_thread()
{
cout << "子线程开始执行" << endl;
}
int main()
{
thread t1(hello_thread);
//子线程结束
t1.join();
//主线程开始执行
cout << "主线程开始执行" << endl;
return 0;
}
二、有参函数
//有参函数
int msum(int a,int b)
{
int c = a + b;
cout << "子线程运行:" << c << endl;
return c;
}
int main()
{
thread t2(msum, 1, 2);
//主线程等待子线程结束
t2.join();
//主线程开始进行工作
cout << "主线程开始工作" << endl;
}
在类的内部创建线程:
三、类的内部为静态函数
class HelloThread
{
public:
static void hellothread()
{
cout << "子线程开始运行"<<endl;
}
static void start()
{
thread t3(hellothread);
t3.join();
}
};
int main()
{
HelloThread::start();
cout << "主线程开始进行运行";
return 0;
}
四、类内部函数在类外部创建线程
class HelloWorld
{
public:
void hello(int year)
{
cout << "I am "<<year<<" years old"<<endl;
}
};
int main()
{
HelloWorld obj;
thread thrd(bind(&HelloWorld::hello,&obj,3));
//子线程开始进行释放
thrd.join();
cout << "主线程开始进行运行";
return 0;
}
五、 join()和detach()的区别:
join()的使用必须是等待子线程运行结束之后,再开始运行主线程。而detach()则是子线程和主线程并发执行,无需等待效果
(1)join()
//join()的执行效果
void hello_thread()
{
cout << "hello Thread!" << endl;
}
int msum(int a, int b)
{
int c = a + b;
cout << a << " +" << b << "=" << c << endl;
return c;
}
int main()
{
thread t1(hello_thread);
//主线程等待子线程运行结束后方可执行到下一步
t1.join();
thread t2(msum,2,3);
t2.join();
//主线程
cout << "主线程开始进行运行";
return 0;
}
(2)detach()的执行效果
//detach()的执行效果
void hello_thread()
{
cout << "hello Thread!" << endl;
}
int msum(int a, int b)
{
int c = a + b;
cout << a << " +" << b << "=" << c << endl;
return c;
}
int main()
{
thread t1(hello_thread);
thread t2(msum, 2, 3);
t1.detach();
t2.detach();
//主线程
cout << "主线程开始进行运行";
return 0;
}
可以看出来detach的执行是并发的
六、 数据同步(线程同时操作一个数据的安全性)
mutex mt;
int data1 = 1;
void addmethod(int a)
{
mt.lock();
data1 += a;
cout << "add data =" << data1 << endl;
mt.unlock();
}
void mult(int a)
{
mt.lock();
data1 *= a;
cout << "mult data =" << data1 << endl;
mt.unlock();
}
int main()
{
thread t1(addmethod,2);
thread t2(mult, 10);
t1.join();
t2.join();
//主线程
cout << "主线程开始进行运行";
return 0;
}