1.join作用
1.1 不加join
#include <iostream>
#include <thread>
#include <mutex>
#include <Windows.h>
using namespace std;
int g_num = 0;
mutex g_mutex;
void thread1()
{
g_num = 50;
for (int i = 0; i < 10; ++i)
cout << "thread1:" << g_num << endl;
}
void thread2()
{
g_num = 100;
for (int j = 0; j < 10; ++j)
cout << "thread2:" << g_num << endl;
}
int main(int argc, char* argv[])
{
thread t1(thread1);
thread t2(thread2);
// Sleep(10000);
system("pause");
return 0;
}
补充说明:关闭窗口时,出现问题,是因为主线程比子线程先退出了,而子线程还没有结束,导致了子线程还没有析构的问题。
1.2 加join()
#include <iostream>
#include <thread>
#include <mutex>
#include <Windows.h>
using namespace std;
int g_num = 0;
mutex g_mutex;
void thread1()
{
g_num = 50;
for (int i = 0; i < 10; ++i)
cout << "thread1:" << g_num << endl;
}
void thread2()
{
g_num = 100;
for (int j = 0; j < 10; ++j)
cout << "thread2:" << g_num << endl;
}
int main(int argc, char* argv[])
{
thread t1(thread1);
thread t2(thread2);
t1.join();
t2.join();
system("pause");
return 0;
}
补充说明:关闭窗口,正常退出。join()会阻塞主线程,就是说t1和t2完成后,才会回到主线程调用system("pause"); 程序继续往后执行。
2.mutex作用
2种添加互斥的方法都可以实现对数据的保护,保证一个线程里的数据不会收到另一个线程的影响。
mutex::lock和mutex::unlock之间的数据进行保护;而lock_guard<mutex>对析构前所在作用域内的数据进行保护。
#include <iostream>
#include <thread>
#include <mutex>
#include <Windows.h>
using namespace std;
int g_num = 0;
mutex g_mutex;
void thread1()
{
g_mutex.lock();
g_num = 50;
for (int i = 0; i < 10; ++i)
cout << "thread1:" << g_num << endl;
g_mutex.unlock();
}
void thread2()
{
//用这种方式更安全
lock_guard<mutex>lg(g_mutex);
g_num = 100;
for (int j = 0; j < 10; ++j)
cout << "thread2:" << g_num << endl;
}
int main(int argc, char* argv[])
{
thread t1(thread1);
thread t2(thread2);
t1.join();
t2.join();
Sleep(10000);
system("pause");
return 0;
}