c++ 并发编程(二)

今天继续看一下并发编程的内容,线程间共享数据。

直接看代码:

线程间共享数据

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <thread>

void hello() {
std::cout << "hello cpp concurrency !" << std::endl;
}
int main(int argc, const char * argv[]) {
std::thread my_thread(hello);
my_thread.join(); // 等待,防止 主线程退出,而子线程还在运行。注意如果有异常也要处理。最好使用RAII处理。
// my_thread.detach(); 通常为守护线程。
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
#include <iostream>
#include <thread>

void hello(std::string& str) {
str = "123";
}

int main(int argc, const char * argv[]) {
std::string s("abc");
std::thread my_thread(hello, std::ref(s)); // std::ref
my_thread.join();
std::cout << s << std::endl;
return 0;
}

// 成员函数
class X {
public:
void do_lengthy_work();
};
X my_x;
std::thread t(&X::do_lengthy_work,&my_x); //