Thread
开启一个线程
使用c++11开启一个线程是比较简单的,如下:
#include<iostream>
#include<thread>
using namespace std;
void hello()
{
cout<<"hello kitty"<<endl;
}
int main()
{
std::thread t(hello);
t.join();
return 0;
}
输出结果:
也可以通过函数对象的方式
#include<iostream>
#include<thread>
using namespace std;
class Say_hello
{
public:
void operator()(){cout<<"hello";}
};
int main()
{
Say_hello hello;
std::thread t(hello);
t.join();
return 0;
}
输出结果:
带参数的函数
当函数自身有参数时,形参可以直接写在开启线程的函数参数的后面,如:
thread t( function , t1 , t2 , ...)
比如说下面这2个例子
#include<iostream>
#include<thread>
using namespace std;
class Say_hello
{
public:
enum {times = 2};
void operator()(int n = times)
{
for(int i=0;i!=n;i++)
cout<<"hello"<<endl;
}
};
int main()
{
Say_hello hello;
std::thread t(hello);
t.join();
return 0;
}
不带参数时,输出结果为:
带参数时,输出结果为:
int main()
{
Say_hello hello;
std::thread t(hello,5);
t.join();
return 0;
}
锁的实现
多线程为了实现线程安全,当访问共享数据时,要避免几个线程同时访问,以免造成竞争条件(race condition)
下面举了一个简单的例子,用锁来实现同步。
一共10张票,开4个线程来卖票。
#include<iostream>
#include<thread>
#include<mutex>
using namespace std;
int tickets_count = 10;
mutex a_mutex;
void sale()
{
lock_guard<mutex> guard(a_mutex);
//a_mutex.lock();
while(tickets_count>0)
{
cout<<tickets_count--<<endl;
}
//a_mutex.unlock();
}
int main()
{
std::thread t1(sale);
std::thread t2(sale);
std::thread t3(sale);
std::thread t4(sale);
t1.join();
t2.join();
t3.join();
t4.join();
return 0;
}
如果不加锁,可能造成重复,输出混乱(std::out 也不是线程安全)
通过对临界区加锁来尽量实现线程安全。
输出结果为: