c++11多线程小记

C++11标准库里添加了多线程和锁的库,简单的使用小例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
using namespace std;
#include<Windows.h>
#include<thread>
void ( char c)
{
for( int i = 0; i < 1000; i++ )
{
cout << c;
cout.flush();
Sleep(1);
}
}
int main()
{
std::thread *a = new std::thread(PrintThread, 'a');
std::thread *b = new std::thread(PrintThread, 'b');
a->join();
b->join();
char c;
cin >> c;
return 0;
}

引入锁:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
using namespace std;
#include<mutex>
#include<thread>
std::mutex m;
void ( char data )
{
char c = data;
for( int i = 0; i < 200; i++ )
{
m.lock();
for( int j = 0; j < 50; j++ )
{
cout << c;
cout.flush();
}
m.unlock();
}
}
int main()
{
std::thread a,b;
//std::thread *a = new std::thread( PrintThread, 'a' );
//std::thread *b = new std::thread( PrintThread,'b' );
a = std::thread(PrintThread, 'a');
b= std::thread(PrintThread, 'b');
a.join();
b.join();
char c;
cin >> c;
return 0;
}