优缺点对比: 多线程开销小,但难于管理,且不能用于分布式系统; 多进程开销大,操作系统会进行一部分管理,因此用户管理就比较简单,可用于分布式; 通常多线程和多进程结合使用。 参考资料:http://edu.csdn.net/course/detail/2303/35894?auto_start=1 [TOC] 代码实例:
下面的代码是非线程安全的,主线程和t1线程将竞争资源cout,只要竞争到资源就随时可以将内容写入到输出流cout,使得输出看起来是下面这样的:
from t1: 0 from t1: -1 from t1: -2 from main: 0 from main: 1 from main: 2 from main: 3 from main: 4 from main: 5 from main: 6 from main: 7 from t1: -3 from t1: -4 from t1: -5
#include <iostream> #include <thread> #include <string> using namespace std; void function_1() { for(int i = 0; i > -100; --i) { cout << "from t1: " << i << endl; } } int main() //主线程 { std::thread t1(function_1); for(int i = 0; i < 100; ++i) { cout << "from main: " << i << endl; } t1.join(); //主线程将等待t1线程结束后再运行 return 0; }可以加mutex锁,有线程正在使用cout,其他线程就不能使用,这样cout在当前程序中是线程安全的,能使得输出是有序的,是下面这样的:
from main: 0 from t1: 0 from main: 1 from t1: -1 from main: 2 from t1: -2 from main: 3 from t1: -3 from main: 4 from t1: -4 from main: 5 from t1: -5
#include <iostream> #include <thread> #include <string> #include <mutex> using namespace std; std::mutex mtx; void shared_print(string s, int id) { mtx.lock(); cout << s.c_str() << id << endl; mtx.unlock(); } void function_1() { for(int i = 0; i > -100; --i) { shared_print("from t1: ",i); } } int main() //主线程 { std::thread t1(function_1); for(int i = 0; i < 100; ++i) { shared_print("from main: ",i); } t1.join(); //主线程将等待t1线程结束后再运行 return 0; }上面的代码中,当shared_print函数中cout那一行抛出异常时,mtx.unclock()不会被执行,mtx将被永远地锁住。这时可以使用std::lock_guard来保证mtx会被解锁。shared_print函数修改如下:
void shared_print(string s, int id) { std::lock_guard<std::mutex> locker(mtx); //lock_guard对象创建时会自动对mtx加锁,离开作用域被析构时,mtx会被自动解锁,这样即使cout这行发生异常,mtx也能被解锁了 cout << s.c_str() << id << endl; }但是上面的代码仍然不是安全的,因为cout是个全局变量,并没有完全在mtx的保护下,其他线程仍然可以在不加锁的情况下使用cout。为了完整地保护资源,必须使资源和互斥对象进行绑定。代码如下:
#include <iostream> #include <thread> #include <string> #include <mutex> #include <fstream> using namespace std; class LofFile { public: LofFile() { f.open("log.txt"); } void shared_print(string s, int id) { std::lock_guard<std::mutex> locker(m_mutex); f << s << id << endl; } private: std::mutex m_mutex; std::ofstream f; }; void function_1(LofFile& log) { for(int i = 0; i > -100; --i) { log.shared_print("from t1: ",i); } } int main() //主线程 { LofFile log; std::thread t1(function_1, std::ref(log)); for(int i = 0; i < 100; ++i) { log.shared_print("from main: ",i); } t1.join(); //主线程将等待t1线程结束后再运行 return 0; }上面的代码将资源std::ofstream f和互斥对象std::mutex m_mutex定义在LogFile类中,类外的线程不可访问资源f,使用类对象的shared_print函数的线程也能保证资源f必定有一个互斥对象m_mutex来保护。简单地讲,就是资源和互斥对象必定成对地出现在同一个作用域中,因此资源一定会受互斥对象保护。注意,这里的代码使用了资源std::ofstream f,而不是cout,是因为cout是全局的资源。
死锁是指两个线程互相锁住,互相等待释放,却不能释放,下面的代码发生了死锁,程序的输出可能是这样的(程序被暂停在某处,并没有成功执行完毕):
from t1: 0 from main: 0 from t1: -1 from main: 1
#include <iostream> #include <thread> #include <string> #include <mutex> #include <fstream> using namespace std; class LofFile { public: LofFile() { f.open("log.txt"); } void shared_print(string s, int id) //函数被t1线程调用 { std::lock_guard<std::mutex> locker(m_mutex); std::lock_guard<std::mutex> locker2(m_mutex2); cout << s << id << endl; //为了更直观得看到结果,这里改成cout } void shared_print2(string s, int id) //函数被主线程调用 { std::lock_guard<std::mutex> locker2(m_mutex2); std::lock_guard<std::mutex> locker(m_mutex); cout << s << id << endl; //为了更直观得看到结果,这里改成cout } //如果t1线程执行到锁住m_mutex时,主线程正好执行到锁住m_mutex2,t1线程继续执行下一语句发现m_mutex2被锁住了,于是等待m_mutex2被解锁,而主线程也继续执行下一语句发现m_mutex被锁住了,于是等待m_mutex被解锁,两个线程相互等待,这样就发生了死锁,程序就一直暂停在哪里 private: std::mutex m_mutex; std::mutex m_mutex2; std::ofstream f; }; void function_1(LofFile& log) { for(int i = 0; i > -100; --i) { log.shared_print("from t1: ",i); } } int main() //主线程 { LofFile log; std::thread t1(function_1, std::ref(log)); for(int i = 0; i < 100; ++i) { log.shared_print2("from main: ",i); } t1.join(); //主线程将等待t1线程结束后再运行 return 0; }上面的代码中,m_mutex和m_mutex2在两个线程中加锁的顺序是相反的,如果将语句的顺序改成一致就不会发生死锁。在C++标准库中提供了std::lock,是规范的处理死锁问题的方法,把上面的两个函数改成下面这样:
void shared_print(string s, int id) //函数被t1线程调用 { std::lock(m_mutex, m_mutex2); //std::lock可以指定锁的顺序,参数为lock1,lock2,...,lockn,它的参数个数是不固定的,有多少个锁就可以使用多少个参数 std::lock_guard<std::mutex> locker(m_mutex, std::adopt_lock); //这里添加std::adopt_lock是告知locker,m_mutex已经被锁住,locker要做的只是获得m_mutex的所有权,然后在析构时将其解锁即可 std::lock_guard<std::mutex> locker2(m_mutex2, std::adopt_lock); cout << s << id << endl; //为了更直观得看到结果,这里改成cout } void shared_print2(string s, int id) //函数被主线程调用 { std::lock(m_mutex, m_mutex2); std::lock_guard<std::mutex> locker2(m_mutex2, std::adopt_lock); std::lock_guard<std::mutex> locker(m_mutex, std::adopt_lock); cout << s << id << endl; //为了更直观得看到结果,这里改成cout }上面的代码中,即使locker和locker2的顺序是相反的,但是m_mutex和m_mutex2加锁的顺序是相同的,因为std::lock指定了加锁的顺序。 为了避免程序设计中出现死锁,可以遵循以下几条规则: (1)使用一个mutex即可满足要求的场合,绝不使用两个mutex; (2)如果某个作用域中已经使用了一个mutex,那么要小心该作用域中的函数调用,因为该函数调用中可能包括其他mutex; (3)无法避免地需要使用两个以上mutex时,尽量使用std::lock指定锁的顺序,但是在某些极端情况下std::lock无法使用,就要小心地保证加锁的语句顺序。
上面使用的所有示例代码中,LogFile类都是在构建函数中打开log.txt文件,如果我们想只在调用shared_print函数的时候才打开文件,可以做如下修改:
class LogFile { public: LogFile() { //f.open("log.txt"); } void shared_print(string s, int id) { //if(!f.is_open()) //这段代码不是线程安全的,因为两个线程可能同时执行到f.open处,两次打开文件,将会运行报错 //{ // f.open("log.txt"); //} //if(!f.is_open()) //这段代码仍然不是线程安全的,假设a线程尚未执行完f.open,b线程正好检测到文件未打开,然后发现m_mutex_fopen被锁住,于是等待,接着a线程打开了文件,解锁m_mutex_fopen,此时b线程发现解锁了,立即执行f.open,这样就两次打开文件,将会运行报错 //{ // std::unique_lock<std::mutex> locker(m_mutex_fopen, std::defer_lock); // f.open("log.txt"); //} //{ //这段代码是线程安全的,但是这存在一个性能上的问题,即每次函数调用都要对m_mutex_fopen进行加锁和解锁,这会无意义地消耗计算机资源 // std::unique_lock<std::mutex> locker(m_mutex_fopen, std::defer_lock); // if(!f.is_open()) f.open("log.txt"); //} std::call_once(m_flag, [&](){f.open("log.txt")}) //这行代码能确保后面的lambda函数只被一个线程调用一次,是C++标准库的推荐用法 std::unique_lock<std::mutex> locker(m_mutex, std::defer_lock); f << s << id << endl; } private: std::mutex m_mutex; std::mutex m_mutex_fopen; std::once_flag m_flag; std::ofstream f; };条件变量适用于a线程需要等待b线程触发某种条件,a线程才能执行的场合
#include <iostream> #include <thread> #include <string> #include <mutex> #include <fstream> #include <deque> #include <functional> #include <condition_variable> using namespace std; std::deque<int> q; std::mutex mu; std::condition_variable cond; void function_1() { int count = 10; while (count > 0) { std::unique_lock<mutex> locker(mu); q.push_front(count); locker.unlock(); cond.notify_one(); //激活条件变量cond cond.notify_all(); //notify_one只能激活一个正在等待cond被激活的线程 //notify_all可以激活所有正在等待cond被激活的线程 std::this_thread::sleep_for(chrono::seconds(1)); count--; } } void function_2() { int data = 0; while (data != 1) { std::unique_lock<mutex> locker(mu); /*if (!q.empty()) { data = q.back(); q.pop_back(); locker.unlock(); cout << "t2 got a value from t1: " << data << endl; } else //当q为空时,一直在执行while循环,不断查询,直到q非空,这样是很低效的,应该使用条件变量 { locker.unlock(); }*/ //等待线程1调用notify_one()激活条件变量bond,只有cond被激活,才可以 //执行后面的语句。此处locker作为参数传递给wait之前已经加锁了,一个 //线程不会在锁住的情况下休眠,所以wait()先将mu解锁,使其休眠,然后 //又加锁。由于需要重复加解锁,所以此处得用unique_lock,而不能使用 //lock_guard //某些情况下,线程可能被自己激活,这称为伪激活,给条件变量添加一个 //lambda函数作为增加的一个条件,满足条件才可以被激活 cond.wait(locker, [](){return !q.empty(); }); data = q.back(); q.pop_back(); locker.unlock(); cout << "t2 got a value from t1: " << data << endl; } } int main() { std::thread t1(function_1); std::thread t2(function_2); t1.join(); t2.join(); return 0; }std::future类可以从子线程获取返回值,然后在父线程中使用
#include <iostream> #include <thread> #include <string> #include <mutex> #include <fstream> #include <future> using namespace std; int factorial(int N) { int res = 1; for (int i = N; i > 1; --i) { res *= i; } cout << "Result is: "<< res << endl; return res; } int main() { int x; //std::thread t1(factorial,4); //t1.join(); //有时希望将子线程的执行结果返回给父线程,可以修改上面的代码将x的引用 //传给t1,通过内存共享的方式来实现,但是更简单的方式是使用future对象, //取名future的含义是,这个对象可以从未来获取某个值,即等待未来子线程执 //行结束时返回的值。实际上async并不一定会创建子线程,如果明确指定第一 //个参数为std::launch::deferred,将不创建子线程,此时factorial()调用将被延期, //等到get()执行后,就在父线程中调用factorial。如果参数为std::launch::async, //就是明确指定创建子线程。async的参数默认是std::launch::async | std::launch::deferred, //意思是是否创建子线程将取决于实现(没有弄明白取决于什么实现?) //std::future<int> fu = std::async(factorial, 4); std::future<int> fu = std::async(std::launch::async | std::launch::deferred, factorial, 4); x = fu.get(); //get将会等待子线程结束,并取回子线程返回的结果,get只能被调用一次,调用两次程序会运行报错 return 0; }std::promise可以从父线程获取值到子线程中使用
#include <iostream> #include <thread> #include <string> #include <mutex> #include <fstream> #include <future> using namespace std; int factorial(std::future<int>& f) { int N = f.get(); int res = 1; for (int i = N; i > 1; --i) { res *= i; } cout << "Result is: "<< res << endl; return res; } int main() { int x; std::promise<int> p; std::future<int> f = p.get_future(); std::future<int> fu = std::async(std::launch::async, factorial, std::ref(f)); p.set_value(4); //这里必须进行set_value,否则在factorial函数的int N = f.get()这行会抛出std::future_error::broken_promise的异常 x = fu.get(); cout << "Get from child: " << x << endl; return 0; }如果需要创建多个都调用factorial线程,每个线程都需要一个f参数,但是std::future不能被拷贝,此时可以使用std::shared_future,它可以被拷贝,可将int factorial(std::future& f)改为int factorial(std::shared_future f),同时main函数做如下修改:
int main() { int x; std::promise<int> p; std::future<int> f = p.get_future(); std::shared_future<int> sf = f.share(); std::future<int> fu = std::async(std::launch::async, factorial, sf); std::future<int> fu2 = std::async(std::launch::async, factorial, sf); std::future<int> fu3 = std::async(std::launch::async, factorial, sf); p.set_value(4); return 0; }可以让某个类对象休眠一段时间,或者到达指定的时间点才停止休眠
#include <iostream> #include <thread> #include <string> #include <mutex> #include <fstream> #include <future> #include <deque> using namespace std; int factorial(int N) { int res = 1; for (int i = N; i > 1; --i) { res *= i; } cout << "Result is: " << res << endl; return res; } int main() { std::thread t1(factorial, 6); std::this_thread::sleep_for(chrono::milliseconds(3)); //线程休眠3毫秒 chrono::steady_clock::time_point tp = chrono::steady_clock::now() + chrono::milliseconds(3); //一个静态的时间点 std::this_thread::sleep_until(tp); //一直休眠,直到达到指定的时间点tp,才结束休眠 std::mutex mu; std::unique_lock<std::mutex> locker(mu); locker.try_lock_for(chrono::milliseconds(3)); locker.try_lock_until(tp); std::condition_variable cond; cond.wait_for(locker, chrono::milliseconds(3)); cond.wait_until(locker, tp); std::promise<int> p; std::future<int> f = p.get_future(); f.wait_for(chrono::milliseconds(3)); f.wait_until(tp); }