C++中创建线程以及使用

参考博客:https://blog.csdn.net/ouyangfushu/article/details/80199140?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task

以下内容就是参照以上博主的博客:

头文件:#include<iostream>
#include <thread>
#include <mutex>

一、无参函数

//无参函数
void hello_thread()
{
	cout << "子线程开始执行" << endl;
}
int main()
{
	thread t1(hello_thread);
	//子线程结束
	t1.join();
	//主线程开始执行
	cout << "主线程开始执行" << endl;
	return 0;

}

二、有参函数

//有参函数
int msum(int a,int b)
{
	int c = a + b;
	cout << "子线程运行:" << c << endl;
	return c;
}

int main()
{
	thread t2(msum, 1, 2);
	//主线程等待子线程结束
	t2.join();
	//主线程开始进行工作
	cout << "主线程开始工作" << endl;
}

在类的内部创建线程:

三、类的内部为静态函数

class HelloThread
{
public:
	static void hellothread()
	{
		cout << "子线程开始运行"<<endl;
	}
	static void start()
	{
		thread t3(hellothread);
		t3.join();
	}
};

int main()
{
	HelloThread::start();
	cout << "主线程开始进行运行";
	return 0;
}

四、类内部函数在类外部创建线程

class HelloWorld
{
public:
    void hello(int year)
	{
		cout << "I am "<<year<<" years old"<<endl;
	}
};

int main()
{
	HelloWorld obj;
	thread thrd(bind(&HelloWorld::hello,&obj,3));
	//子线程开始进行释放
	thrd.join();
	cout << "主线程开始进行运行";
	return 0;
}

五、 join()和detach()的区别:

join()的使用必须是等待子线程运行结束之后,再开始运行主线程。而detach()则是子线程和主线程并发执行,无需等待效果

(1)join()

//join()的执行效果
void hello_thread()
{
	cout << "hello Thread!" << endl;
}

int msum(int a, int b)
{
	int c = a + b;
	cout << a << " +" << b << "=" << c << endl;
	return c;
}
int main()
{
	thread t1(hello_thread);
	//主线程等待子线程运行结束后方可执行到下一步
	t1.join();
	thread t2(msum,2,3);
	t2.join();
	//主线程
	cout << "主线程开始进行运行";
	return 0;
}

(2)detach()的执行效果

//detach()的执行效果
void hello_thread()
{
	cout << "hello Thread!" << endl;
}

int msum(int a, int b)
{
	int c = a + b;
	cout << a << " +" << b << "=" << c << endl;
	return c;
}
int main()
{
	thread t1(hello_thread);
	thread t2(msum, 2, 3);
	t1.detach();
	t2.detach();
	//主线程
	cout << "主线程开始进行运行";
	return 0;
}

可以看出来detach的执行是并发的

六、 数据同步(线程同时操作一个数据的安全性)

mutex mt;
int data1 = 1;

void addmethod(int a)
{
	mt.lock();
	data1 += a;
	cout << "add data =" << data1 << endl;
	mt.unlock();
}

void mult(int a)
{
	mt.lock();
	data1 *= a;
	cout << "mult data =" << data1 << endl;
	mt.unlock();
}

int main()
{
	thread t1(addmethod,2);
	thread t2(mult, 10);
	t1.join();
	t2.join();
	//主线程
	cout << "主线程开始进行运行";
	return 0;
}

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值