Thread使用

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值