一、使用线程类——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行进行注释,就是没加锁了。效果如下
很明显,不加锁的时候,操作是无序的。
当然,线程顺序,可能有更好的方法去保证,这里暂不讨论,下次有机会写博客补上。
==============