c++多线程学习笔记(1)

一、使用线程类——thread创建线程的简单实例

#include <thread>
 
void func()
{
   // do some work
}
 
int main()
{
   std::thread t(func);
   t.join();
 
   return 0;
}


而且,如果func()是有参数的,那么在创建thread类的实例 t 的时候,直接传参即可。

例如 void func(int x){};  那么就可以有  std::thread t(func, 8);  

如果有多个参数,也是一样的直接写后面。


二、使用互斥锁——mutex

有时候,多个线程,可能都需要操作某个变量,但是大家又希望,在某个线程进行操作的时候,其他线程不要去动它,或者说大家希望各个线程可以有顺序的去操作,例如线程1操作一个变量,线程2就不能操作这个变量。等线程1做完事情,线程2再继续操作。

(1)使用mutex加锁

#include "stdafx.h"
#include <thread>
#include <iostream>
#include <vector>
#include <mutex>
#include <Windows.h>

std::mutex mt;
int g_num = 0;

void func1(){
	mt.lock();
	while (1){
		++g_num;
		std::cout << "this is thread 1 , g_num = " << g_num << std::endl;
		Sleep(2000);
	}
	mt.unlock();
}

void func2(){
	mt.lock();
	while (1){
		g_num = g_num + 10;
		std::cout << "this is thread 2 , g_num = " << g_num << std::endl;
		Sleep(2000);
	}
	mt.unlock();
}

int main(){

	std::thread th1(func1);
	std::thread th2(func2);

	th1.join();
	th2.join();

	getchar();
	return 0;

}

//


(2)不加锁
为代码的12行,18行,22行,28行进行注释,就是没加锁了。效果如下




很明显,不加锁的时候,操作是无序的。

当然,线程顺序,可能有更好的方法去保证,这里暂不讨论,下次有机会写博客补上。


==============

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值