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;
}
点击查看代码
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;
}
点击查看代码
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<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;
}
浙公网安备 33010602011771号