不合理的设定临界区域,会让线程的调用失去意义。
1.不应该频繁的使用锁
2.减小锁使用的区域,线程公共资源之外 的资源 尽量不要放到临界区。
-------------------------------------------------------------------------------------------------------
示例一:(这样使用线程锁,设定的临界区域不合理,会让线程的调用失去意义,线程并没有并发执行)
#include <iostream> #include <thread> #include <mutex> using namespace std; mutex m_lock; int sum = 0; void workFun(int index) { m_lock.lock(); for (int i = 0; i < 1000; i++) { sum++; cout << "thread:"<<index << " sum=" << sum<<endl; } m_lock.unlock(); }//抢占式 int main() { thread t[3]; for (int n = 0; n<3; n++) { t[n] = thread(workFun, n); } for (int n = 0; n<3; n++) { t[n].join(); } cout << "sum=" << sum << endl; cout << "i am main thread " << endl; return 0; }
----------------------------------------------------------------------------------------------------------
示例二:(不用线程)
#include <iostream> #include <thread> #include <mutex> using namespace std; mutex m_lock; int sum = 0; void workFun() { for (int i = 0; i < 300000; i++) { sum++; } }//抢占式 int main() { thread t[3]; workFun(); cout << "sum=" << sum << endl; cout << "i am main thread " << endl; return 0; }
示例三:(使用线程,并且加锁)
#include <iostream> #include <thread> #include <mutex> using namespace std; mutex m_lock; int sum = 0; void workFun(int index) { for (int i = 0; i < 100000; i++) { m_lock.lock(); sum++; m_lock.unlock(); } }//抢占式 int main() { thread t[3]; for (int n = 0; n<3; n++) { t[n] = thread(workFun, n); } for (int n = 0; n<3; n++) { t[n].join(); } cout << "sum=" << sum << endl; cout << "i am main thread " << endl; return 0; }
示例三的耗时 会比 示例二的耗时大,所以要慎用多线程,慎用锁。设计不好的多线程反而会更耗时。