C++多线程初步学习

开多线程时用到thread,一个线程可以调用一个函数,为了防止我们创建的子线程会在主线程结束前没有跑完,所以我们要让主线程等待子线程执行完毕再继续主线程,使用join()
同时如果想要在子线程中对一个变量进行修改时,需要通过ref()来传入参数

点击查看代码
void fun(int &a)
{
	cout << "thread is running..." << endl;
	a = 1100;
}
void test()
{
	cout << "test is running..." << endl;
}
int main()
{
	thread t(test);
	t.join();//等等t子线程执行完
	int a = 10;
	thread t1(fun, ref(a));
	t1.join();//等等t1子线程执行完
	cout << "now a==" << a << endl;
	cout << "Hello World!" << endl;
	
	return 0;
}
但是有个问题,如果有两个线程同时要访问修改同一个变量,那怎么确定哪个线程先访问并修改,并且另一个线程不会在期间影响呢,这时候要用互斥锁mutex 如果mutex.lock()上锁后,就能保证目前只有这一个线程能访问这个锁作用域内的变量,而其他线程如果也用到了这个锁,那就只能等待目前的线程解锁后才开始运行
点击查看代码
void fun(int &a)
{
	mtx.lock();
	cout << "thread fun is running..." << endl;
	a = 1100;
	mtx.unlock();
}
void fun2(int& a)
{
	mtx.lock();
	cout << "thread fun2 is running..." << endl;
	a = 300;
	mtx.unlock();
}
int main()
{
	int a = 10;
	thread t1(fun, ref(a));
	thread t2(fun2, ref(a));
	t1.join();//等等t1子线程执行完
	t2.join();//等等t2子线程执行完
	cout << "now a==" << a << endl;
	cout << "Hello World!" << endl;
	
	return 0;
}
不过有个lock_guard可以和mutex搭配实现区域内的自动解锁,不需要手动unlock()解锁,还有个问题就是虽然可能先创建的t1线程后创建的t2线程,但是可以t1线程会后执行,这就是cpu的问题了
点击查看代码
mutex mtx;
void fun(int &a)
{
	lock_guard<mutex> lock(mtx);//自动上锁,离开作用域自动解锁
	cout << "thread fun is running..." << endl;
	a = 1100;
}
void fun2(int& a)
{
	lock_guard<mutex> lock(mtx);//自动上锁,离开作用域自动解锁
	cout << "thread fun2 is running..." << endl;
	a = 300;
}
int main()
{
	int a = 10;
	thread t1(fun, ref(a));
	thread t2(fun2, ref(a));
	t1.join();//等等t1子线程执行完
	t2.join();//等等t2子线程执行完
	cout << "now a==" << a << endl;
	cout << "Hello World!" << endl;
	
	return 0;
}
还有如果只是单独的在线程中访问修改一个变量,如果不想用锁的话,可以用原子操作atomic,可以保证这个变量只能在一个线程中被修改 当然只是简单的访问变量,如果复杂的话还是需要用互斥锁
点击查看代码
atomic<int> a(10);//原子操作,不需要加锁,线程安全,保证a只会在一个线程中被修改
void fun(int &a)
{
	cout << "thread fun is running..." << endl;
	a = 1100;
}
void fun2(int& a)
{
	cout << "thread fun2 is running..." << endl;
	a = 300;
}
int main()
{
	thread t1(fun, ref(a));
	thread t2(fun2, ref(a));
	t1.join();//等等t1子线程执行完
	t2.join();//等等t2子线程执行完
	cout << "now a==" << a << endl;
	cout << "Hello World!" << endl;
	
	return 0;
}

posted on 2026-06-09 13:52  dd_l  阅读(4)  评论(0)    收藏  举报